liveBook · Manning

Fwrite

As explained in Modern C, Third Edition

fwrite is a C standard-library function that writes a specified number of objects from memory to a stream.

fwrite writes size*nmemb bytes from a memory buffer to the current position of a stream. Its prototype accepts a pointer, object size, object count, and FILE stream; the return value reports how many bytes were written, usually size*nmemb. 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 the prototype listing to compare fwrite with fread, fseek, and ftell: these interfaces operate on the same stream position. section 14.6

Writing an in-memory byte array

unsigned char data[] = { /* binary data */ }; size_t written = fwrite(data, 1, sizeof data, stdout); Here, fwrite requests one-byte objects and writes sizeof data bytes to stdout. A result smaller than the requested amount indicates that the write did not complete successfully. section 14.6 section 14.6

For portable binary I/O, open the stream in binary mode. Binary mode suppresses translation between the file’s external representation and the program’s internal bytes; without it, a program can work on one platform and fail on another. section 14.6 section 14.7

The stream’s file position advances after a successful write. Combine fwrite with fread, ftell, and fseek to move through a binary file and preserve an object’s internal representation for later reading. section 14.6

How Modern C, Third Edition covers it

How deep it goes
Explains the prototype, byte counts, stream-position updates, short writes, and binary-mode portability, but not implementation internals.
Examples
Uses a memory byte array, stdout, file-position navigation, and writing an object’s internal representation.
What it assumes
Assumes familiarity with memory buffers, FILE streams, and basic C types such as size_t.
What you can do after
Apply it via the C standard library to write complete binary buffers and detect incomplete transfers.
How it connects
Connects fwrite with fread, fseek, ftell, streams, binary mode, and object representations.

Also explained in

Compare how 2 books explain fwrite →

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.