File Handling · intermediate · ~8 min
Read text lines without buffer overflow.
char *fgets(char *buf, int n, FILE *f) reads at most n-1 chars or up to and including a \n, NUL-terminates the buffer, and returns buf (or NULL on EOF/error). This is the safe way to read user-supplied text.
The included \n lets you detect short reads vs. exact-fit lines. Strip it if you don't want it.
char line[256];
while (fgets(line, sizeof line, stdin)) {
line[strcspn(line, "\n")] = 0; // strip newline
/* process line */
}
n as bytes-to-read; it reads at most n-1 (leaves room for NUL).