Created
June 30, 2013 18:29
-
-
Save clsr/5896303 to your computer and use it in GitHub Desktop.
read a line until a newline or EOF, allocating and resizing an array as necessary
This file contains hidden or 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 <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#define READ_LINE_BUFFER 1024 | |
char *read_line(FILE *f) | |
{ | |
char *line, *l; | |
size_t linelen; | |
char buf[READ_LINE_BUFFER]; | |
size_t len; | |
line = NULL; | |
linelen = 0; | |
while (!feof(f) && !ferror(f)) { | |
if (!fgets(buf, (READ_LINE_BUFFER), f)) break; | |
len = strlen(buf); | |
l = realloc(line, linelen + len + 1); | |
if (!l) { | |
if (line) free(line); | |
return NULL; | |
} | |
line = l; | |
strcpy(line+linelen, buf); | |
linelen += len; | |
if (line[linelen-1] == '\n') { | |
break; | |
} | |
} | |
return line; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment