Lines, boundaries, and checked parsing
Separate input acquisition, complete-record boundaries, text conversion, and application validation.
In this chapter7 sections
Reading text and accepting a valid value are separate jobs. First establish which bytes belong to one complete input record. Then parse them and check the permitted range. Keeping those steps separate makes rejected input easier to handle.
1. fgets returns a chunk, not a complete-record guarantee
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char chunk[8];
if (fgets(chunk, sizeof chunk, stdin) == NULL) {
if (ferror(stdin)) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
if (fputs(chunk, stdout) == EOF) return EXIT_FAILURE;
return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
With this positive capacity of eight, fgets reads at most seven characters and appends a null terminator on success. A newline is retained if it is read. With 12345678 followed by a newline, the first chunk contains only 1234567; the eighth character and newline remain unread. The example is deliberately only a first-chunk demonstration for input without embedded NUL characters.
A successful chunk without a newline can mean a final unterminated line, a line that exactly fills the available space, or an overlong record whose remainder still exists. A simple “no newline means too long” test is incomplete. Conversely, a read failure is not a valid empty string: if EOF arrives before any character, fgets leaves the array unchanged; on a read error its contents are indeterminate. Use the buffer only after success.
2. Choose the record and length contract explicitly
Our next reader accepts at most seven C bytes before a newline, removes the line separator, accepts a nonempty final line without a newline, and distinguishes an empty line from immediate EOF. It rejects a line containing NUL because the next stage uses null-terminated strings. Even on rejection it consumes through the separator or EOF, so the next request starts at the next record.
- Acquire
- Did reading succeed?
- Frame
- Was the complete record within the limit?
- Convert
- Does the text represent a value?
- Validate
- Is that value allowed here?
Read the complete bounded-line example
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
enum LineResult { LINE_OK, LINE_END, LINE_TOO_LONG, LINE_NUL, LINE_ERROR };
/* capacity >= 1; buffer has capacity writable characters; stream is readable. */
static enum LineResult read_line(FILE *stream, char *buffer, size_t capacity)
{
size_t used = 0;
bool saw_data = false, too_long = false, has_nul = false;
int ch;
while ((ch = fgetc(stream)) != EOF && ch != '\n') {
saw_data = true;
if (ch == '\0') { has_nul = true; continue; }
if (used < capacity - 1) ((unsigned char *)buffer)[used++] = (unsigned char)ch;
else too_long = true;
}
buffer[used] = '\0';
if (ch == EOF && ferror(stream)) return LINE_ERROR;
if (ch == EOF && !saw_data) return LINE_END;
if (has_nul) return LINE_NUL;
if (too_long) return LINE_TOO_LONG;
return LINE_OK;
}
int main(void)
{
char line[8];
for (;;) {
enum LineResult result = read_line(stdin, line, sizeof line);
if (result == LINE_END) break;
if (result == LINE_ERROR) return EXIT_FAILURE;
if (result == LINE_TOO_LONG) {
if (puts("too long") == EOF) return EXIT_FAILURE;
} else if (result == LINE_NUL) {
if (puts("NUL rejected") == EOF) return EXIT_FAILURE;
} else {
if (printf("line=[%s]\n", line) < 0) return EXIT_FAILURE;
}
}
return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
The helper requires a live readable byte-oriented stream, at least one writable buffer element, and its actual capacity. It keeps the int result until EOF/newline checks, stores the byte representation through an unsigned-char view rather than converting to a possibly narrower plain-char value, preserves room for the terminator, and stops storing when full while continuing to drain the record. Check its status before using line contents: a rejected line’s stored prefix is not accepted input. An I/O error takes priority over other classifications.
The capacity counts C bytes, not Unicode code points or user-perceived characters. This reader does not validate a text encoding. This approach detects input NUL before building the string. A later strlen cannot reveal how many characters fgets consumed past an embedded NUL; successful fgets alone does not establish a NUL-free text contract. For huge records, draining may itself require a resource policy such as a byte/time limit supplied by the application or platform. The helper is a bounded-storage teaching design, not a universal network protocol parser.
3. Convert text, then enforce the application range
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
static bool parse_score(const char *text, int *result)
{
if (text == NULL || result == NULL) return false;
char *end = NULL;
errno = 0;
long value = strtol(text, &end, 10);
if (end == text || errno == ERANGE) return false;
while (isspace((unsigned char)*end)) ++end;
if (*end != '\0' || value < 0 || value > 100) return false;
*result = (int)value;
return true;
}
int main(int argc, char *argv[])
{
int score = 0;
if (argc != 2 || !parse_score(argv[1], &score)) return EXIT_FAILURE;
if (printf("score=%d\n", score) < 0) return EXIT_FAILURE;
return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
This parser accepts a decimal score from zero through one hundred with optional surrounding whitespace and an optional sign. The command-line wrapper makes the conversion easy to inspect independently; the same helper can receive a LINE_OK string from the bounded reader. End-pointer equality rejects no conversion, ERANGE rejects an unrepresentable long result, and the trailing scan rejects text outside the chosen whitespace policy.
The isspace argument is converted through unsigned char. The application range fits every standard int, so the final cast follows a representability proof instead of preceding it. A failure leaves the result object unchanged. This policy differs deliberately from the earlier command-line example that rejected trailing whitespace; choosing a policy is part of designing the input contract.
4. Publish state only after a valid record
Reading, conversion, and domain checks can report different failures without corrupting a previously accepted score. Keep a candidate in a temporary object, then call the module’s validated setter only after every check succeeds. An empty record, clean EOF, invalid number, overlong line, embedded NUL, and I/O error are different outcomes; the interface decides which permit retry, which end input normally, and which terminate with failure.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 7.21.7.1–7.21.7.2, 7.21.10, 7.22.1.4, 7.4, 6.3.1.3. Stable core provisions used for the C17 baseline; not the final ISO publication.
Before you move on
- A complete input record must be separated from chunks returned by an input call.
- Parsing should distinguish valid data, incomplete input, invalid text, and out-of-range values.
- Accepted values should be committed only after the required checks succeed.
Keep these ideas separate
- Buffer full / Record complete
- A full read buffer can contain only part of a logical line; the boundary policy decides what remains to be read.
How would you reject an overlong line while leaving the next input record ready to read?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Yes, a terminating null proves the whole line fitted.
Null termination does not prove that a newline or the entire logical line was consumed.
- Yes, the buffer size automatically grows.
fgets does not dynamically enlarge the supplied buffer.
- No. The buffer can fill before the line ends.
✓ Correct reasoning. Detect and handle incomplete lines according to the input policy.
C17
Ready for the next idea?
Mark this chapter as read whenever you feel ready.