Skip to content

Instantly share code, notes, and snippets.

@clsr
Created June 30, 2013 18:29
Show Gist options
  • Save clsr/5896303 to your computer and use it in GitHub Desktop.
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
#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