Robust Integer Input in C: EOF, Truncation and strtol
Robust integer input needs a record boundary and an error contract, not just a conversion function. A caller should be able to distinguish clean EOF, invalid syntax, an overlong line, and an I/O failure—and know whether the next call starts at the next record.
The reusable API below reads one decimal integer per line. It rejects embedded null bytes, bounds its memory use, checks the full int range, and consumes the remainder of rejected records. Its driver processes multiple lines so recovery is visible.
Define the API contract first
read_decimal_int_line(FILE *stream, int *result) requires valid, non-null pointers and a readable stream that is byte-oriented or still unoriented, without a concurrent reader. It changes *result only when it returns INPUT_OK.
| Status | Meaning | Stream position |
|---|---|---|
INPUT_OK | Complete, valid integer | After newline or at EOF |
INPUT_EOF | No new record before clean EOF | At EOF |
INPUT_INVALID | Bad syntax, range, or byte | Rejected record consumed |
INPUT_TOO_LONG | More than 63 data characters | Rejected record consumed |
INPUT_IO_ERROR | Existing or newly detected stream error | Recovery is not guaranteed |
The newline delimiter does not count toward the 63-character limit. Spaces, signs, and leading zeros do. Counts apply to characters delivered by fgetc, after any text-stream translation. The API does not change stream mode or clear error indicators; callers that require exact physical bytes should open their file in binary mode.
Complete implementation and multi-line driver
The accepted syntax is optional basic C whitespace, an optional sign, one or more decimal digits, and optional trailing whitespace. Hexadecimal prefixes, decimal fractions, grouping separators, and extra tokens are rejected. The lexical check keeps this grammar independent of additional numeric forms a locale might recognize.
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
typedef enum {
INPUT_OK, INPUT_EOF, INPUT_INVALID,
INPUT_TOO_LONG, INPUT_IO_ERROR
} InputStatus;
enum { MAX_LINE = 63 };
static int basic_space(unsigned char c)
{
return c == ' ' || c == '\t' || c == '\n' ||
c == '\r' || c == '\v' || c == '\f';
}
static InputStatus parse_decimal_int(const char text[], int *result)
{
const char *p = text, *digits;
char *end;
long value;
/* Enforce basic decimal syntax, even outside the C locale. */
while (basic_space((unsigned char)*p))
++p;
if (*p == '+' || *p == '-')
++p;
digits = p;
while (*p >= '0' && *p <= '9')
++p;
if (p == digits)
return INPUT_INVALID;
while (basic_space((unsigned char)*p))
++p;
if (*p != '\0')
return INPUT_INVALID;
errno = 0;
value = strtol(text, &end, 10);
if (end == text || errno == ERANGE)
return INPUT_INVALID;
while (basic_space((unsigned char)*end))
++end;
if (*end != '\0' || value < INT_MIN || value > INT_MAX)
return INPUT_INVALID;
*result = (int)value;
return INPUT_OK;
}
/* Preconditions: stream and result are valid, non-null pointers.
stream is a readable byte stream with no concurrent reader. */
InputStatus read_decimal_int_line(FILE *stream, int *result)
{
char text[MAX_LINE + 1];
size_t used = 0;
int ch, saw_data = 0, too_long = 0, invalid_byte = 0;
if (ferror(stream))
return INPUT_IO_ERROR;
while ((ch = fgetc(stream)) != EOF && ch != '\n') {
int accepted = basic_space((unsigned char)ch) ||
ch == '+' || ch == '-' ||
(ch >= '0' && ch <= '9');
saw_data = 1;
if (!accepted)
invalid_byte = 1; /* Includes embedded null bytes. */
if (used < MAX_LINE)
text[used++] = accepted ? (char)ch : '?';
else
too_long = 1;
}
if (ch == EOF && ferror(stream))
return INPUT_IO_ERROR;
if (ch == EOF && !saw_data)
return INPUT_EOF;
if (too_long)
return INPUT_TOO_LONG;
if (invalid_byte)
return INPUT_INVALID;
text[used] = '\0';
return parse_decimal_int(text, result);
}
static const char *status_name(InputStatus status)
{
switch (status) {
case INPUT_OK: return "OK";
case INPUT_EOF: return "EOF";
case INPUT_INVALID: return "INVALID";
case INPUT_TOO_LONG: return "TOO_LONG";
case INPUT_IO_ERROR: return "IO_ERROR";
}
return "UNKNOWN";
}
int main(void)
{
int value;
InputStatus status;
for (;;) {
status = read_decimal_int_line(stdin, &value);
if (status == INPUT_OK)
printf("OK %d\n", value);
else
puts(status_name(status));
if (status == INPUT_EOF)
return EXIT_SUCCESS;
if (status == INPUT_IO_ERROR)
return EXIT_FAILURE;
}
}
The driver continues after invalid or overlong records. It exits successfully at clean EOF and with failure on an I/O error. A record being invalid therefore does not by itself set the driver's final exit status.
Why read characters instead of trusting a string prefix?
A line may contain a null byte before its actual end. Passing that buffer straight to string functions could validate only the prefix. This reader observes every input character, marks disallowed bytes—including nulls—and still finishes consuming the record. It stores a harmless placeholder for rejected bytes, so only representable basic characters are converted to char.
fgetc returns an int; keeping that return type lets the loop compare against EOF before storing a character. Reaching EOF is distinguished from a read failure using ferror. These interfaces are specified in the C11 draft, sections 7.21.7.1 and 7.21.10. For context on embedded nulls in string-based line input, see the GNU libc line-input reference.
Walk through the exact buffer boundary
The array has 64 elements: 63 for record data and one for the terminating null. The loop does not stop when storage fills. It marks the 64th data character as overlong, then drains through the delimiter or EOF.
| Input record | Result | Reason |
|---|---|---|
61 spaces + 42 + newline | OK 42 | Exactly 63 data characters |
61 spaces + 42 + EOF | OK 42 | Valid final unterminated record |
62 spaces + 42 | TOO_LONG | 64 data characters |
| Empty line | INVALID | A record exists, but has no digits |
| Immediate EOF | EOF | No record exists |
On a stream that delivers \r\n unchanged, the carriage return counts as data and is allowed as trailing whitespace. On a text stream that translates it to \n, only the delimiter is delivered. This matters when specifying exact capacity tests.
Check strtol before narrowing to int
strtol returns a long. Clear errno before calling it, check ERANGE, inspect the end pointer, and only then consider the value. Zero is a valid result and cannot serve as a failure signal. The GNU libc integer-parsing reference explains these separate checks.
A representable long does not necessarily fit in int. If long is 64 bits and int is 32, 2147483648 fits the first type but not the second. When both are 32 bits, conversion already exceeds the long range. This API checks INT_MIN and INT_MAX before casting, covering both models. Type ranges depend on the compiler and target; use the limits.h bounds. The tests here used 32-bit int and long; wider-long execution is not claimed.
The base argument is explicitly 10. Consequently, 010 means decimal ten. The syntax check rejects 0x10 rather than treating it as hexadecimal or accepting just its initial zero.
Actual output and recovery tests
For this input:
18
18abc
+00042
The compiled driver produced:
OK 18
INVALID
OK 42
EOF
A separate run supplied 200 copies of 1, a newline, then 7 and a newline. Its output demonstrates resynchronization:
TOO_LONG
OK 7
EOF
Error precedence is deliberate: I/O failure wins over other conditions; otherwise excessive length wins over invalid content. An overlong line containing a null therefore returns TOO_LONG. No failed call changes the output integer.
Cost, limits, and integration
Memory use is constant. Time is linear in the consumed record length, including discarded characters. Bounded storage does not create a deadline: blocking input or an endless line can keep a call running. A network-facing reader needs its transport's size/time policy outside this stdio API.
TinyCC 0.9.27 on Windows x64 compiled the code with warnings as errors. It passed 35 driver cases, five output-parameter probes, and one Windows-specific injected read-error probe. Those cover null-byte rejection, record recovery, syntax and integer bounds, exact capacity, EOF, and sticky I/O errors.
To integrate the API into the arithmetic progression example, add the exercise's positive term-count limit only after INPUT_OK. Keep record parsing separate from application rules. For comparison with formatted input, the existing main(), scanf(), and printf() article introduces that interface.
No comments