File Handling · intermediate · ~8 min

fgets for safe line reading

Read text lines without buffer overflow.

Lesson

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.

Code examples

char line[256];
while (fgets(line, sizeof line, stdin)) {
    line[strcspn(line, "\n")] = 0;  // strip newline
    /* process line */
}

Common mistakes

  • Treating fgets's n as bytes-to-read; it reads at most n-1 (leaves room for NUL).