Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read line from file without knowing the line length

Tags:

c

file-io

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;     length++; }  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)?

--Ry

like image 771
ryyst Avatar asked Mar 28 '10 09:03

ryyst


1 Answers

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.     length++; } . . free(buffer); 

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

like image 121
codaddict Avatar answered Sep 28 '22 01:09

codaddict