Skip to content

Instantly share code, notes, and snippets.

@hugopeixoto
Created July 5, 2015 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugopeixoto/f16f1ae0d0bfbcfe1bd0 to your computer and use it in GitHub Desktop.
Save hugopeixoto/f16f1ae0d0bfbcfe1bd0 to your computer and use it in GitHub Desktop.
size_t
readlines(FILE* in, char ***items) {
char buf[BUFSIZ], *p;
size_t i, size = 0;
/* read each line from stdin and add it to the item list */
for(i = 0; fgets(buf, sizeof buf, in); i++) {
if(i+1 >= size / sizeof **items)
if(!(*items = realloc(*items, (size += BUFSIZ))))
die("cannot realloc %u bytes:", size);
if((p = strchr(buf, '\n')))
*p = '\0';
if(!((*items)[i] = strdup(buf)))
die("cannot strdup %u bytes:", strlen(buf)+1);
}
if(*items)
(*items)[i] = NULL;
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment