The parser from the last two lessons works on one line in a buffer. Getting that line from stdin safely is its own problem. The input decides how long a line is, and the buffer does not grow. fgets reads at most one buffer's worth, so a 300-character line arrives as several pieces. If the program treats each piece as a record, one bad line becomes three or four rejections, and the tail of a long line might even parse as a valid record. The goal of this lesson is exact accounting: every input line counts once, as accepted or rejected, and the next line starts fresh.
Predict and run
The input box for this program is empty. Read the program before pressing Run and predict what it prints for empty input.
#include <stdio.h>
#include <string.h>
int main(void) {
char line[8];
size_t lines = 0;
while (fgets(line, sizeof line, stdin) != NULL) {
if (strchr(line, '\n') == NULL && !feof(stdin)) {
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) { }
}
++lines;
}
printf("%zu\n", lines);
return 0;
}Check your prediction
0With no input, the first fgets returns NULL and the loop body never runs. Now open the input box, type a 20-character line followed by a line ok, and run again. It prints 2: the long line counts once, because the inner loop throws away the rest of it.
What fgets actually does
fgets(line, sizeof line, stdin) reads characters until it has stored sizeof line - 1 of them, or it has stored a newline, or input ends. It always writes a terminator after what it read, so with an 8-byte buffer you get at most 7 characters. It returns NULL when it could read nothing at all, either at end of input or on a read error.
So after a successful call there are three possibilities:
- The buffer contains
'\n': a complete line, including its newline. - No newline, and
feof(stdin)is true: the last line of the input, which had no newline. It is complete. - No newline, and not at end of input: the line was longer than the buffer. The rest is still waiting in the stream.
The condition strchr(line, '\n') == NULL && !feof(stdin) picks out the third case exactly.
Drain the rest, then count once
For an overlong line, the program reads and discards characters until it consumes the newline or reaches the end:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) { }ch must be an int, not a char. getchar returns every possible byte as a non-negative value, plus the separate value EOF, which is negative. Stored in a char, either a real byte would be mistaken for EOF (where char is signed) or EOF would never be seen and the loop would never end (where char is unsigned). After draining, count one rejection and continue, so the fragment never reaches the parser.
The exact boundary
With an 8-byte buffer, which lines are "too long"? A line of 6 characters plus its newline needs 7 bytes plus the terminator: it fits. A line of exactly 7 characters fills the buffer, and its newline is still in the stream, so it is treated as overlong. The rule is therefore "a line fits if its characters and its newline fit in size - 1 bytes". A last line of exactly 7 characters with no newline is rejected too: fgets stopped at the limit before it could see the end of input. The project's 96-byte buffer allows lines of up to 94 characters, far more than a valid record needs.
Line endings and blank lines
Windows files end lines with "\r\n"; the parser treats '\r' as whitespace, so reading 25\r\n is accepted. A blank line holds only "\n", has no topic and counts as one rejection. Empty input has no lines at all, so the report prints No records and three zeros. Test both cases.
Check why the loop ended
fgets returns NULL both at end of input and on a read error. After the loop, ferror(stdin) tells them apart. The project's main checks it and treats a read error as fatal, because a report built from half the input would be misleading.
Practice
Your turn
Read stdin with a 16-byte buffer. For each complete line, remove its line ending ("\n" or "\r\n") and print it in brackets. Count overlong lines without printing them. At the end, print complete C, too long T, and print read error instead if ferror(stdin) is true. With the prefilled input the output must be [reading 25], [], [ok], complete 3, too long 1. With empty input it must be complete 0, too long 0.
#include <stdio.h>
#include <string.h>
int main(void) {
char line[16];
// Read, classify and count each line.
return 0;
}Hint 1: the idea
Decide what kind of line you have before you touch its contents. Only a complete line has its ending removed and printed; an overlong one is drained, counted and skipped with continue.
Hint 2: a first step
First write the loop that only classifies: print complete or too long for each fgets piece, and drain the overlong ones. Check the four results against the input before you touch the line endings. Then look for a <string.h> function that finds the first of several characters, and use its answer to cut the line.
Show one solution
#include <stdio.h>
#include <string.h>
int main(void) {
char line[16];
size_t complete = 0, too_long = 0;
while (fgets(line, sizeof line, stdin) != NULL) {
if (strchr(line, '\n') == NULL && !feof(stdin)) {
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) { }
++too_long;
continue;
}
line[strcspn(line, "\r\n")] = '\0';
printf("[%s]\n", line);
++complete;
}
if (ferror(stdin)) {
puts("read error");
return 1;
}
printf("complete %zu, too long %zu\n", complete, too_long);
return 0;
}With the prefilled input this prints [reading 25], [], [ok] and complete 3, too long 1. The long line is drained in one go, so its tail never appears as a bracketed line. The blank line prints as [], and the final ok is complete even without a newline, because feof is true when fgets returns it. With an empty input box it prints complete 0, too long 0. The checkpoint next joins this loop to the topic and number parsers to validate a whole record.
Completion is saved in this browser only. It does not measure mastery.