Reputation: 93
I've starting tinkering around with the Fread/Fwrite functions within C. I'm basically working on a program that manipulates data on a CSV file for my month end accounting task. For my CSV files, the fread()
function appears to (generally) work properly. I can effectively stream the CSV file onto the screen etc. Occasionally, I get a read error on certain bytes of data fread()!=counted/buffered item and tosses an error.
Out of curiosity, I've run my program on non-CSV files, specifically a .png
file. The file appears to run correctly on my program. I can tell this is the case as my program operates as it did for the CSV file. I've set the file up to tell me the stats (size in characters), etc., in another function that I've created. I've also set up a program that tells me the number of letters/characters the file has (a to z). When I run the picture file, the program seems to normally fill in the statical details from above; however, when I try to view the stream, nothing shows up other than a png and question mark. I would have expected a ton of garbage to show up at a minimum, yet I get nothing. Why is the stream not showing anything, despite the above statistical data appearing to show up? I'm wondering if it has something to do with the buffer or some kind of internal operating system thing.
Upvotes: 0
Views: 117
Reputation: 753455
Put simply, fread()
is most appropriate for binary data. A CSV file is not binary data, so fread()
is usually not appropriate.
It does depend on what you're going to do with the data you read. If you're simply copying it to standard output (the terminal), it may be OK.
If you get a partial read on the last block of the file, it isn't an error — it is reality jumping up and letting you know that the file size was not a multiple of the block size you're using to read the data. Print the data that was read and, usually, don't bother with trying to read more. You could wait until you get zero back from fread()
before stopping (so have another try). That might be appropriate if the input is coming from a pipe, for example.
Be careful what you choose as the output mechanism. If the data was read with fread()
and you do not modify it, using fwrite()
is probably appropriate. Otherwise, watch for null bytes in the data — especially if the input is not text.
Upvotes: 2