liveBook · Manning

Fread

As explained in Modern C, Third Edition

fread is a C standard-library function that reads a specified number of objects from a stream into memory.

fread reads size*nmemb bytes from the current position of a stream into memory. On success, it advances that position and returns the number of bytes read; a smaller return indicates an error or incomplete read. section 14.6

 size_t fread(void* restrict ptr, size_t size, size_t nmemb,
              FILE* restrict stream);
 size_t fwrite(void const*restrict ptr, size_t size, size_t nmemb,
               FILE* restrict stream);
 int fseek(FILE* stream, long int offset, int whence);
 long int ftell(FILE* stream);

The declaration exposes fread's four arguments: destination memory, object size, object count, and input stream. section 14.6

Reading a file byte-for-byte

FILE* inp = fopen(__FILE__, "rb"); if (inp) { size_t ibytes = fread(there, 1, sizeof there, inp); cmp = memcmp(here, there, sizeof here); fclose(inp); } Here, size is 1, so fread requests sizeof there bytes. The file is opened with "rb": binary mode prevents text-stream translation. The result is recorded in ibytes and compared with the expected byte array. section 14.6

TAKEAWAY rules:

  • Open streams in binary mode when reading binary data portably; otherwise, platform-specific end-of-line translation can alter the data. section 14.6
  • Check the return value against the requested byte count; a smaller value means the complete request was not satisfied. section 14.6
  • Combine fread with fseek and ftell when navigation through a file stream requires moving forward or backward. section 14.6

How Modern C, Third Edition covers it

How deep it goes
Defines the interface, byte-count semantics, position updates, return checking, and binary-mode restriction, but does not detail error categories.
Examples
Demonstrates reading the current source file into an array, comparing byte arrays, and reporting input and output counts.
What it assumes
Assumes familiarity with streams, files, arrays, and memory buffers while reinforcing binary mode and stream-position handling.
What you can do after
Operate/configure it by opening a binary stream, supplying a destination and byte count, checking the result, and closing the stream.
How it connects
Connects binary streams with fwrite, fseek, ftell, file positions, and binary-mode file opening.

Also explained in

Compare how 2 books explain fread →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.