Changeset 6ace255


Ignore:
Timestamp:
Oct 15, 2009, 8:00:07 PM (14 years ago)
Author:
Karl Ramm <kcr@1ts.org>
Branches:
master, release-1.10, release-1.5, release-1.6, release-1.7, release-1.8, release-1.9
Children:
946058b
Parents:
30b634a
git-author:
Karl Ramm <kcr@1ts.org> (09/24/09 10:39:08)
git-committer:
Karl Ramm <kcr@1ts.org> (10/15/09 20:00:07)
Message:
owl_getline, owl_getline_chomp, and owl_slurp

For the glorious replacement of fgets into fixed buffers!
(realistically, should eventually use getline if it's there)
File:
1 edited

Legend:

Unmodified
Added
Removed
  • util.c

    rf119757 r6ace255  
    781781  return g_string_free(out, 0);
    782782}
     783
     784/* innards of owl_getline{,_chomp} below */
     785static int owl_getline_internal(char **s, FILE *fp, int newline)
     786{
     787  int size = 0;
     788  int target = 0;
     789  int count = 0;
     790  int c;
     791
     792  while (1) {
     793    c = getc(fp);
     794    if ((target + 1) > size) {
     795      size += BUFSIZ;
     796      *s = owl_realloc(*s, size);
     797    }
     798    if (c == EOF)
     799      break;
     800    count++;
     801    if (c != '\n' || newline)
     802        (*s)[target++] = c;
     803    if (c == '\n')
     804      break;
     805  }
     806  (*s)[target] = 0;
     807
     808  return count;
     809}
     810
     811/* Read a line from fp, allocating memory to hold it, returning the number of
     812 * byte read.  *s should either be NULL or a pointer to memory allocated with
     813 * owl_malloc; it will be owl_realloc'd as appropriate.  The caller must
     814 * eventually free it.  (This is roughly the interface of getline in the gnu
     815 * libc).
     816 *
     817 * The final newline will be included if it's there.
     818 */
     819int owl_getline(char **s, FILE *fp)
     820{
     821  return owl_getline_internal(s, fp, 1);
     822}
     823
     824/* As above, but omitting the final newline */
     825int owl_getline_chomp(char **s, FILE *fp)
     826{
     827  return owl_getline_internal(s, fp, 0);
     828}
     829
     830/* Read the rest of the input available in fp into a string. */
     831char *owl_slurp(FILE *fp)
     832{
     833  char *buf = NULL;
     834  char *p;
     835  int size = 0;
     836  int count;
     837
     838  while (1) {
     839    buf = owl_realloc(buf, size + BUFSIZ);
     840    p = &buf[size];
     841    size += BUFSIZ;
     842
     843    if ((count = fread(p, 1, BUFSIZ, fp)) < BUFSIZ)
     844      break;
     845  }
     846  p[count] = 0;
     847
     848  return buf;
     849}
Note: See TracChangeset for help on using the changeset viewer.