View Full Version : C using fread to read an unknown amount of data

12-11-2011, 02:22 AM
Hey guys.

I have a text file called test.txt

Inside it will be a number, it may be as follows:


I.e it could be any size of number, from 1 digit up to x digits.

The file will only have 1 thing in it - this number. I want a bit of code using fread which will read that number of bytes from the file and put it into an appropriately sized variable.

Can anyone suggest the best way to solve this problem?

12-11-2011, 04:47 AM
Let's see the code you have tried writing to solve this.

12-11-2011, 05:04 AM
Somebody suggested:

char buffer[4096];
size_t nbytes = fread(buffer, sizeof(char), sizeof(buffer), fp);

if (nbytes == 0)
...EOF or other error...
...process nbytes of data...

But this seems wasteful of memory as I am running on an embedded device - so want a more neat solution.

Another person suggested using fseek to get to the end of the file, then ftell to work out the cursor position which would equal the number of bytes *most of the time* inless the file changes underneath you.