Last active
January 12, 2019 03:15
-
-
Save jstaursky/4b2b831e967f1d2f5bcb2e7218a40cb7 to your computer and use it in GitHub Desktop.
retrieve arbitrary length strings from a given FILE stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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