C programming stdio.h function - size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
In C programming, the fread()
function is defined in the stdio.h
header file, and is used to read data from a file. The function takes the following four arguments:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
The first argument, ptr
, is a pointer to a block of memory into which the data will be read. The second argument, size
, is the size in bytes of each element to be read. The third argument, nmemb
, is the number of elements to be read. The fourth argument, stream
, is a pointer to a FILE
object that represents the file to be read.
The fread()
function reads data from the file, and stores it in the memory location pointed to by ptr
. It reads a total of nmemb
elements, each size
bytes long, from the file represented by stream
. The total amount of data read is size * nmemb
bytes.
The function returns the number of elements successfully read, which may be less than nmemb
if the end of the file is reached or an error occurs. If an error occurs, the fread()
function returns a value less than nmemb
.
Here's an example of how to use fread()
to read data from a file:
#include <stdio.h> int main() { FILE *fp; char buffer[100]; size_t nread; fp = fopen("example.txt", "r"); if (fp == NULL) { printf("Error opening file.\n"); return 1; } nread = fread(buffer, 1, 100, fp); printf("Read %zu bytes.\n", nread); fclose(fp); return 0; }
In the above example, the fread()
function is used to read up to 100 bytes of data from a file named "example.txt". The data is stored in a buffer of 100 characters, which is passed to the function as the first argument. The second argument is 1
, indicating that each element to be read is one byte long. The third argument is 100
, indicating that the maximum number of elements to be read is 100. If the end of the file is reached before 100 bytes have been read, the fread()
function will return the number of bytes actually read.