liveBook · Manning

Byte stream

As explained in Modern C, Third Edition

A binary stream is a C stream that transfers data as sequences of bytes without text-oriented character transformations.

A byte stream transfers file data without text-oriented translation. Opened in binary mode, it preserves each byte between the file and the C program, avoiding changes such as platform-specific end-of-line conversion. section 14.6

Use the stream interfaces according to the operation:

  • Use fread and fwrite to transfer size*nmemb bytes from the current file position; their return value counts bytes transferred, so a smaller count signals an error. section 14.6
  • Use ftell to obtain the byte position and fseek with SEEK_SET or SEEK_CUR to move relative to the file start or current position. section 14.6
  • For portable binary handling, open the stream in binary mode; among the previously introduced interfaces, fgetc and fputc handle binary files portably. section 14.6

Comparing a source file byte for byte

A binary-mode program opens __FILE__ with fopen(__FILE__, "rb"), reads it with fread, compares the result using memcmp, writes embedded bytes with fwrite, and reports the input and output counts. 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 core binary-stream API combines byte-counted transfer with explicit file-position control. section 14.6

How Modern C, Third Edition covers it

How deep it goes
Explains representation translation, byte counts, error detection, and file positioning through fread, fwrite, ftell, and fseek.
Examples
Uses an embedded source array, binary reading of __FILE__, memcmp, and writing bytes to stdout.
What it assumes
Assumes familiarity with pointers and C streams rather than teaching those concepts from zero.
What you can do after
Operate/configure binary file I/O with fopen, fread, fwrite, ftell, and fseek.
How it connects
Connects binary mode, C streams, fread, fwrite, ftell, fseek, and file position.

Also explained in

Compare how 3 books explain byte stream →

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.