fgets in C: Reading Bounded Lines from stdin and FILE Streams

For line-oriented text input, the safest and most predictable standard library function is fgets in c, which is found in stdio.h. In c, fgets gets 3 arguments: the char buffer, the max number of bytes to be read (usually the size of the buffer), and the input stream (usually stdin), and reads at most capacity-1 characters, followed by a null terminator. Also, note that fgets in c leaves the '\n' terminator in the buffer if the line is shorter than the buffer, which can be cleaned up with a call to strcspn(buffer, "\n") = '\0', and that it is better to loop on fgets(buffer, sizeof buffer, fp) != NULL than to check feof in advance.

fgets in C: Safe Line Input, Newline Stripping & EOF Loop Pattern — Technical Overview

For line-oriented text input, the safest and most predictable standard library function is fgets in c, which is found in stdio.h. In c, fgets gets 3 arguments: the char buffer, the max number of bytes to be read (usually the size of the buffer), and the input stream (usually stdin), and reads at most capacity-1 characters, followed by a null terminator. Also, note that fgets in c leaves the '\n' terminator in the buffer if the line is shorter than the buffer, which can be cleaned up with a call to strcspn(buffer, "\n") = '\0', and that it is better to loop on fgets(buffer, sizeof buffer, fp) != NULL than to check feof in advance.

#include <stdio.h>
#include <string.h>

int main(void) {
    char buf[64] = "Hello from fgets\n";
    buf[strcspn(buf, "\n")] = '\0';
    printf("Trimmed line: "%s" (length=%zu)\n", buf, strlen(buf));
    return 0;
}

Runnable C example

#include <stdio.h>
#include <string.h>

int main(void) {
    char buf[64] = "Hello from fgets\n";
    buf[strcspn(buf, "\n")] = '\0';
    printf("Trimmed line: "%s" (length=%zu)\n", buf, strlen(buf));
    return 0;
}

Open example in compiler

Expected Output

Trimmed line: "Hello from fgets" (length=16)