← File I/O and Standard LibraryC PROGRAMMING 1.5.B

Reading and Writing

fread/fwrite/fprintf/fscanf and buffering behavior.

StatusCollected
NotesChapter test: 5/5

The actual read/write calls, and the buffering layer sitting between them and the disk that I hadn't really thought about before this chapter.

char buf[128];
fgets(buf, sizeof(buf), f);          /* read a line, bounded by buffer size */

fprintf(f, "%d,%s\n", id, name);     /* formatted write, same idea as printf */

size_t n = fread(buf, 1, sizeof(buf), f);   /* raw bytes, for binary data */
fwrite(data, sizeof(int), count, f);

fprintf/fscanf are formatted, text-oriented; fread/fwrite move raw bytes and are the ones actually used for binary data. Both go through stdio's own internal buffer first — a write doesn't necessarily hit disk the instant it's called, which is what fflush or fclose is for when the timing of the write actually matters.

Notes from readers

Comments — via GitHub