liveBook · Manning

File position

As explained in Modern C, Third Edition

A file position is the location within a stream at which the next read or write occurs.

A file position is the location in a stream at which the next read or write occurs. Successful fread and fwrite operations transfer bytes from that position and advance it. 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);

Use fread and fwrite to transfer bytes, ftell to inspect the position, and fseek to reposition it. section 14.6

The core rules are:

  • fread and fwrite return the number of bytes transferred; a result below size*nmemb indicates an error or incomplete operation. section 14.6
  • ftell reports the position in bytes from the file start, while fseek moves it using an offset and whence such as SEEK_SET or SEEK_CUR. section 14.6
  • Open streams in binary mode when using this interface portably; otherwise platform-specific end-of-line translation can change the data. section 14.6

Reading a file as bytes

A program can open a file with fopen(__FILE__, "rb"), read it with fread, compare the bytes, and write bytes with fwrite. Repositioning permits moving forward or backward through the file. section 14.6

How Modern C, Third Edition covers it

How deep it goes
Defines position and explains fread, fwrite, ftell, and fseek behavior, stopping short of broader positioning restrictions.
Examples
Demonstrates opening a source file in binary mode, reading it into an array, comparing bytes, and writing them to standard output.
What it assumes
Assumes familiarity with C streams and introduces the current position maintained for stream reading and writing.
What you can do after
Operate/configure it via C stream functions to transfer bytes and move between file positions.
How it connects
Connects file position with binary streams, fread, fwrite, ftell, fseek, and byte-oriented file traversal.

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.