Implementation status: partially implemented


#include <stdio.h>

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);


The fread() function reads data from the given stream into the array pointed to by ptr.


ptr - an array saving the read data,
size - a size of an unique item,
nmemb - a number of items to read,
stream - the input stream.

The fread() function reads into the array pointed to by ptr up to nmemb elements whose size is specified by size in bytes, from the stream pointed to by stream. For each object, size calls are made to the fgetc() function and the results stored, in the order read, in an array of unsigned char exactly overlaying the object. The file position indicator for the stream (if defined) is advanced by the number of bytes successfully read. If an error occurs, the resulting value of the file position indicator for the stream is unspecified. If a partial element is read, its value is unspecified.

The fread() function may mark the last data access timestamp of the file associated with stream for update. The last data access timestamp is marked for update by the first successful execution of fgetc(), fgets(), fread(), fscanf(), getc(), getchar(), getdelim(), getline(), gets(), or scanf() using stream that returns data not supplied by a prior call to ungetc().

Return value

Upon successful completion, fread() returns the number of elements successfully read which is less than nmemb only if a read error or end-of-file is encountered. If size or nitems is 0, fread() returns 0 and the contents of the array and the state of the stream remain unchanged.
Otherwise, if a read error occurs, the error indicator for the stream is set, and errno is set to indicate the error.


[EAGAIN] The O_NONBLOCK flag is set for the file descriptor underlying stream and the thread would be delayed in the fgetc() operation.
[EBADF] The file descriptor underlying stream is not a valid file descriptor open for reading.
[EINTR] The read operation was terminated due to the receipt of a signal, and no data was transferred.
[EIO] A physical I/O error has occurred, or the process is in a background process group attempting to read from its controlling terminal, and either the calling thread is blocking SIGTTIN or the process is ignoring SIGTTIN or the process group of the process is orphaned.
[EOVERFLOW] The file is a regular file and an attempt was made to read at or beyond the offset maximum associated with the corresponding stream.
[ENOMEM] Insufficient storage space is available.
[ENXIO] A request was made of a nonexistent device, or the request was outside the capabilities of the device.

Implementation tasks

  • Implement error handling for the function