Skip to content

Instantly share code, notes, and snippets.

@jstaursky
Last active January 12, 2019 03:15
Show Gist options
  • Save jstaursky/4b2b831e967f1d2f5bcb2e7218a40cb7 to your computer and use it in GitHub Desktop.
Save jstaursky/4b2b831e967f1d2f5bcb2e7218a40cb7 to your computer and use it in GitHub Desktop.
retrieve arbitrary length strings from a given FILE stream
#include <stdlib.h>
char*
fgetLine(FILE *stream)
{
const size_t chunk = 128;
size_t max = chunk;
/* Preliminary check */
if (!stream || feof(stream))
return NULL;
char *buffer = (char *)malloc(chunk * sizeof(char));
if (!buffer) {
perror("Unable to allocate space");
return NULL;
}
char *ptr = buffer;
int c; /* fgetc returns int. Comparing EOF w/ char may
* cause issues. */
while ( (c = fgetc(stream)) != EOF &&
(*ptr = c) != '\n')
{
++ptr;
size_t offset = ptr - buffer;
if (offset >= max) {
max += chunk;
char *tmp = realloc(buffer, max);
if (!tmp) {
free(buffer);
return NULL;
}
buffer = tmp;
ptr = tmp + offset;
}
}
*ptr = '\0';
return buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment