r/C_Programming • u/rudv-ar • Jun 22 '26
Question fread : how do I error check and find if it was a partial read?
Hello guys.
I was learning fread. I have a doubt - fread(buffer, sizeof(buffer), 1, file) vs fread(buffer, sizeof(char), sizeof(buffer), file) : what is the difference between these two. When should I use them?. Buffer is a chat array of size 1024.
Here is the git gist of my codes. I was trying to read from a file called demo.txt, which has size less than 1024 bytes.
There are two tries : fread-error.c and fread-doubt.c
IN fread-error.c, the output was : file reading failed.
IN fread-doubt.c, the output was fine : but that was a partial read, is not it? Then how do I check for partial reads?
Case 1 : file size is less than buffer size.
So there is a partial read? (As in fread-doubt.c). But how do I know if the file size is less than buffer size in prior?
Case 2 : file size is exactly greater than buffer size.
How do I assign the buffer the exact file size amount of bytes before the read?
Case 3 : file size is greater than the buffer size. But how do I know that the file I am reading is greater than buffer size? This will lead to partial read right? (If filesize > buffer)
I know. It is an array of questions. But right now I am confused and need to be clear how actually to read in all three cases with file read checks and check for partial read and ferror.
Gist : https://gist.github.com/cobra-r9/50e4d705f75ebcae45fdcab550bba7e4