Skip to content

Read a Bounded Line

The Course
•
40 min study

Until now every duration was typed into the source code. A real report reads them from its input, and input is the one thing your program does not control. It may be empty, it may contain words where you expected numbers, and a line may be far longer than you planned for. The oldest input functions in C read into an array with no idea how big the array is, and a long enough line writes past the end of it. That kind of overflow has been behind real security breaches for decades. This lesson uses fgets, which is told the size of the destination and never writes beyond it.

Predict and run

This playground's input box is empty. Predict the output, then run.

Predict before running C
#include <stdio.h>

int main(void) {
    char line[16];
    if (fgets(line, sizeof line, stdin) != NULL) {
        printf("Read: %s", line);
    } else {
        printf("No input\n");
    }
    return 0;
}
Check your prediction
Text
No input

There was nothing to read, so fgets returned NULL and the else branch ran. Now type C and a newline into the input box and run again. It prints Read: C. The format string has no \n after %s, yet the output still ends the line, because the newline from the input is part of the text that fgets stored.

Standard input is a stream

Standard input, stdin, is a stream of characters that the program reads from front to back. On your own computer it might come from the keyboard or from a file. In this playground it comes from the input box, which must be filled in before you press Run; the program cannot pause and wait for you to type. When every character has been read, the stream is at end-of-file, usually shortened to EOF.

What fgets promises

fgets(line, sizeof line, stdin) reads characters into line and stops at the first of three things: a newline (which it stores), end-of-file, or a full buffer. It stores at most sizeof line - 1 characters and always adds a terminator, so the result is a valid string whatever the input looks like. It returns NULL when it could not read anything, at EOF or on an error, and you must then not use the buffer, because it holds nothing new.

That gives three shapes of result to recognize:

  • A complete line ends with '\n'.
  • The last line of the input may have no '\n', because the input simply ended.
  • A line longer than the buffer arrives in pieces. The first piece fills the buffer and has no newline, and the rest of the line is still waiting in the stream.
A long line arrives in pieces C
#include <stdio.h>

int main(void) {
    char line[8];
    int pieces = 0;
    while (fgets(line, sizeof line, stdin) != NULL) {
        pieces++;
        printf("[%s]\n", line);
    }
    printf("Pieces: %d\n", pieces);
    return 0;
}
C long session

With the input above, it prints:

Shell
[C
]
[long se]
[ssion
]
Pieces: 3

Two lines of input produced three reads. The brackets show the newline stored inside the first and last pieces. If each read were treated as one record, long session would count twice and could be half-accepted. The loop shape itself is the standard one: keep calling fgets until it returns NULL.

Recognize and drain a long line

A piece with no newline is an overlong line, unless the stream has reached EOF, in which case it was just a final line without a newline. strchr(line, '\n') from <string.h> returns NULL when the text has no newline, and feof(stdin) tells you whether EOF has been reached. To skip the rest of an overlong line, read single characters with getchar until the newline or EOF. getchar returns an int, not a char, so that it can return every possible character and the separate value EOF.

Here are those three tools working together on one overlong line. Read the program, predict both bracketed lines, then run it.

Drain the rest of a long line C
#include <stdio.h>
#include <string.h>

int main(void) {
    char line[8];
    if (fgets(line, sizeof line, stdin) != NULL) {
        printf("First piece: [%s]\n", line);
        /* strchr: NULL means no newline was stored. feof: has input ended? */
        if (strchr(line, '\n') == NULL && !feof(stdin)) {
            int skipped = 0;
            int ch;
            /* getchar: one character at a time, or EOF when input ends. */
            while ((ch = getchar()) != '\n' && ch != EOF) {
                skipped++;
            }
            printf("Drained %d more characters\n", skipped);
        }
    }
    if (fgets(line, sizeof line, stdin) != NULL) {
        printf("Next read: [%s]\n", line);
    }
    return 0;
}
this line is too long 10
Shell
First piece: [this li]
Drained 14 more characters
Next read: [10
]

Trace it:

  1. fgets stores the first seven characters, this li, plus the terminator. There is no '\n' in them, so strchr returns NULL, and the stream is not at EOF, so the line is overlong.
  2. The drain loop condition does two things in order. (ch = getchar()) reads one character and stores it in ch; the whole parenthesized assignment then has that character as its value, which is compared with '\n'. The parentheses matter: without them, != binds first and ch would get the result of a comparison, 0 or 1, instead of the character.
  3. n, e, , t, … each pass the test and skipped counts them: 14 characters. Then getchar returns '\n', the condition is false and the loop stops, having consumed that newline too.
  4. The next fgets therefore starts at the beginning of the following line and reads 10 and its newline.

Two details make the loop safe. ch is an int because EOF is a negative int that is not any character; stored in a char, it could be confused with a real character or never match at all. And the ch != EOF test stops the loop if the input ends in the middle of the long line, which would otherwise loop forever. This is the one place where the course puts an assignment inside a condition on purpose (Day 2 warned about if (minutes = 0)): here the assignment is wrapped in its own parentheses and compared with !=, which says "read, then test" plainly. When you only need to consume characters, the loop body can be empty, as in while ((ch = getchar()) != '\n' && ch != EOF) { }.

Now delete the whole while loop (keep the printf) and run again. The second read prints [ne is t]: the unread rest of the long line is still waiting, so it would be counted as another record. Put the loop back.

Never read without a bound

gets read a line with no size limit at all; it was so dangerous that it was removed from the language in C11. scanf("%s", line) has the same flaw. Both can write past the end of the array, which is undefined behavior and a security hole. Always pass the real size, and let sizeof compute it, so the bound can never drift from the declaration.

Practice

Exercise

Your turn

Read the whole input with an 8-byte buffer. Count records, meaning input lines, and how many were too long for the buffer. Drain each overlong line so it counts once. With this input, where the last line has no newline:

Shell
25
this line is too long
10

the program prints Records: 3, too long: 1. With empty input it prints Records: 0, too long: 0.

Your workspace C
#include <stdio.h>
#include <string.h>

int main(void) {
    char line[8];
    // Write your solution here.
    return 0;
}
25 this line is too long 10
Hint 1: the idea

Each successful fgets starts a new record. A piece without a newline, read before EOF, means the line was too long: count it, then consume the rest of that line so the next fgets starts on the following line.

Hint 2: a first step

Write the while (fgets(line, sizeof line, stdin) != NULL) loop that only counts records, and run it on the sample input: it says 6, not 3. The 21-character line arrives as this li, ne is t, oo long and a lone newline. Then, inside the loop, add the overlong test from the drain example above with only a printf of the piece in its body. It fires three times, once for each full piece. Draining after the first piece is what should bring both numbers down.

Show one solution
C
#include <stdio.h>
#include <string.h>

int main(void) {
    char line[8];
    int records = 0;
    int long_lines = 0;
    while (fgets(line, sizeof line, stdin) != NULL) {
        records++;
        if (strchr(line, '\n') == NULL && !feof(stdin)) {
            long_lines++;
            int ch;
            while ((ch = getchar()) != '\n' && ch != EOF) {
            }
        }
    }
    printf("Records: %d, too long: %d\n", records, long_lines);
    return 0;
}

With the input box empty, the loop never runs:

Text
Records: 0, too long: 0

With the sample input it prints Records: 3, too long: 1. The final 10 has no newline but is not overlong, and the feof check is what tells those two cases apart. An 8-byte buffer holds at most six visible characters, a newline and the terminator, so any longer line is drained in one go. The next lesson turns a line like 25 into the number 25, and rejects everything else.

Was this article helpful?

Your response is saved on this device.