I am trying to retreive data out of a FILE pointer and into a string. What is the best way to determine the size of the string buffer?
char string[WHAT_SIZE?];
FILE *fp;
fp = fopen("info.dat", "r");
fgets(string, sizeof string, fp);
Do I set the buffer size to something I think is suitable for that particular file? Or is there a more efficient way to do this without using strings with non variable buffer sizes?
In general, You just have to pick a size and go with it. Base the choice on max expected line length or record length or something like that specific to the input type. Just make sure to check return codes and handle the case when the line is longer than you expect.
There are a few tricks you could play to get an exact size, however I can’t remember ever having to use these in practice:
Do a ftell, read char by char, counting until you get to a newline, then allocate enough memory, fseek to rewind, and read the whole line.
Do a fseek to the end of the file to find the size, then rewind and read the whole thing at once into a single buffer.