how to download an unrestricted line from a file using the fread function?

52 views Asked by At

I have a question how to download a line of text from the file without specifying the size of this line? I wouldn't want to use fgets because you have to give the fgets to the characters in advance. I can load the whole file, but not one line.

FILE *f
 long lSize;
 char *buffer;
 size_t result;

f = fopen("file.txt", "r");

 fseek(f, 0, SEEK_END);
 lSize = ftell(f);
 rewind (f);

 buffer = (char*)malloc(sizeof(char)*lSize);

 result = fread(buffer,1,lSize, f);

fclose(f);
free(buffer);

1

There are 1 answers

0
mcleod_ideafix On
  1. Use malloc() to set an initial buffer for your text line. Say, 16 chars.

  2. Loop over the file and retrieve one character at a time with fgetc(). Store it into your buffer, at the appropiate place. If it is a newline, put a NUL character instead in the buffer and exit the loop.

  3. When the buffer is about to get full, realloc() it and expand it for 16 more chars. If the realloc is succesfull, go to step 2.