I have two questions about C’s fread function:
-
I have read that
freadis used to read a binary file. However, when I read a binary file withfgetsusing read mode"r"and a text file withfreadusing"rb"mode, the results are the same as reading a text file withfgetsand a binary file withfread. So, why are there different functions for reading binary and text files? -
I am using
freadto read 10 bytes of a file in one call. How should I stop reading at the end of file – i.e. how isEOFspecified infread?
answer of 1 question >
1>fread
Read block of data from stream (try to understand this)
Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr.
The postion indicator of the stream is advanced by the total amount of bytes read.
The total amount of bytes read if successful is (size * count).
2>fgets
Get string from stream (try to understand this)
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first.
A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str.
A null character is automatically appended in str after the characters read to signal the end of the C string.
answer of 2nd question
in fread return value is
The total number of elements successfully read is returned as a size_t object, which is an integral data type.
If this number differs from the count parameter, either an error occured or the End Of File was reached.
You can use either ferror or feof to check whether an error happened or the End-of-File was reached.