Character I/O: getchar & putchar in C
getchar() reads one character (as int, to represent every char plus EOF) and putchar(c) writes one — the simplest possible I/O pair, and the engine of K&R-style text filters. The int return type is load-bearing: char cannot hold EOF distinctly from 0xFF on some platforms, so int c; while ((c = getchar()) != EOF) is the correct loop shape.
Character I/O looks trivial but teaches buffering truthfully: terminals deliver whole lines (canonical mode), files deliver bytes. Filters compose (prog1 | prog2) precisely because these primitives speak raw streams.
int, not char, for input
int c = getchar(); — EOF (-1) must be distinguishable from every byte value, which char cannot guarantee.
The copy loop
while ((c = getchar()) != EOF) putchar(c); copies stdin to stdout byte-perfectly — the filter archetype.
Count and transform
Increment counters, map cases, collapse whitespace inside the loop — wc, tr, and grep all start here.
Terminals buffer lines
Interactive input arrives per-line (until Enter); files and pipes stream continuously — same code, different pacing.
#include <stdio.h> int main(void) { int c; long n = 0; while ((c = getchar()) != EOF) { if (c == '\n') ++n; } printf("%ld\n", n); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.