1

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);

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Roundstic
  • 21
  • 3
  • Thank you. I'll try to implement it. :) – Roundstic May 17 '20 at 18:12
  • 2
    Do what user3121023 suggested. Now you've the line. If you only want _that_ line, you can trim the buffer to the exact size with: `buffer = realloc(buffer,strlen(buffer) + 1);` Note that: `sizeof(char)` is _always_ `1` (by definition), regardless of the actual bit size of `char` on a given architecture, so you can [and _should_] just do: `buffer = malloc(lSize);` Most arches have 8 bit bytes, but, for example, some TI DSP chips, the minimum addressable unit is 16 bits. So, `char` takes 16 bits, but `sizeof(char)` is _still_ `1` there. – Craig Estey May 17 '20 at 18:27

1 Answers1

2
  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.

mcleod_ideafix
  • 11,128
  • 2
  • 24
  • 32