New Generic pointer that can point to any data type
1st Parameter
Pointer to the buffer where the data read from the file will be stored
2nd Parameter Type : size_t
Platform-specific unsigned type for array indices and memory sizes.
2nd Parameter
The size of each element to be read, in bytes
3rd Parameter Type : size_t
Platform-specific unsigned type for array indices and memory sizes.
3rd Parameter
The number of elements to read
4th Parameter Type : FILE *
Pointer to FILE structure for file operations
4th Parameter
Pointer to the file stream from which data is to be read
Read more about parameters of fread in parameters section
The freadfunction in C language Reads data from the given stream into the array pointed to by ptr.
The fread function reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr. The file position indicator for the stream is advanced by the number of bytes successfully read. This function is commonly used for reading binary data or large chunks of data from files.
To Summarize the Workflow:
1.
Function reads blocks of data from a file stream into memory
2.
Takes four parameters: destination buffer, size of each element, number of elements, stream
3.
Returns number of complete elements successfully read
4.
Returns 0 on EOF before any read or on error
5.
May return less than count if partial read occurs
6.
Works with ferror() and feof() to determine exact cause of failure
Read more about return type and value offread function in return section.
The freadfunction takes 4
parameters:
•
void * `ptr`: Pointer to the buffer where the data read from the file will be stored
•
size_t `size`: The size of each element to be read, in bytes
•
size_t `nmemb`: The number of elements to read
•
FILE * `stream`: Pointer to the file stream from which data is to be read
The fread function return value :
Returns the number of elements successfully read (which may be less than nmemb if a read error or end-of-file is encountered)
If size or nmemb is zero, fread returns zero and the contents pointed to by ptr and the state of the stream remain unchanged
Output
This example demonstrates basic usage of `fread` to read content from a text file. It reads up to 99 bytes from the file into a buffer and then prints the content.