c file-io

Read line from file without knowing the line length

I want to read in a file line by line, without knowing the line length before. Here’s what I got so far:

int ch = getc(file);
int length = 0;
char buffer[4095];
while (ch != '\n' && ch != EOF) {
ch = getc(file);
buffer[length] = ch;
printf("Line length: %d characters.", length);
char newbuffer[length + 1];
for (int i = 0; i < length; i++)
newbuffer[i] = buffer[i];
newbuffer[length] = '\0'; // newbuffer now contains the line.

I can now figure out the line length, but only for lines that are shorter than 4095 characters, plus the two char arrays seem like an awkward way of doing the task.
Is there a better way to do this (I already used fgets() but got told it wasn’t the best way)?


You can start with some suitable size of your choice and then use realloc midway if you need more space as:

int CUR_MAX = 4095;
char *buffer = (char*) malloc(sizeof(char) * CUR_MAX); // allocate buffer.
int length = 0;
while ( (ch != '\n') && (ch != EOF) ) {
if(length ==CUR_MAX) { // time to expand ?
CUR_MAX *= 2; // expand to double the current size of anything similar.
buffer = realloc(buffer, CUR_MAX); // re allocate memory.
ch = getc(file); // read from stream.
buffer[length] = ch; // stuff in buffer.

You’ll have to check for allocation errors after calls to malloc and realloc.