Files & I/O
12 steps in 4 sets of C.
stdio, properly. Opening and reading, writing text and binary, then seeking and the stream behavior that explains why your output appears in the wrong order when you mix printf with write.
Twelve steps, and the buffering set is the one that pays for itself. Line-buffered to a terminal and block-buffered to a pipe is the reason a program's output looks fine interactively and arrives in the wrong order when redirected to a file. Unglamorous, and needed constantly.
Opening & reading
- Opening and closing filesfopen returns NULL on failure, and every successful open needs a matching close.
- Reading lines with fgetsfgets is the safe line reader: it takes a size and always terminates.
- The feof trapfeof reports that a read already failed, so testing it first reads one line too many.
- Reading a whole fileSeek to the end for the size, allocate that plus one, read it back in one call.
Writing & binary
- Writing a formatted reportfprintf writes to any stream with the same format language as printf.
- Binary reads and writesfread and fwrite move records, and both return how many they handled.
- Copying a file in blocksA fixed buffer, read until short, write exactly what was read.
- Temporary filestmpfile gives you a stream that deletes itself when it is closed.
Positioning & streams
- Seeking within a filefseek moves the cursor, ftell reports it, rewind sends it home.
- The three standard streamsstdin, stdout and stderr, and why diagnostics belong on the third.
- errno and perrorWhen a call fails, errno says why, and perror prints it with your prefix.
Encore
- wc_clone.cA word-count clone: read named files or stdin, count lines, words and bytes.