Streams, buffering, and EOF
Understand stream state, standard streams, buffering, read results, and the difference between end-of-file and an error.
In this chapter8 sections
C input and output use streams. A stream connects a program to a sequence of characters, while buffering can delay when work reaches the underlying device. We will follow read results and distinguish end-of-file from an error.
1. A stream carries data and state
A stream is the C library’s input/output abstraction. A FILE object records the information needed to control a stream, such as buffering, position, and status. Use a FILE * through the documented functions; do not copy a FILE object and expect another independent open stream. A stream is also different from a filename or an operating-system file descriptor.
- Program interface
- fgetc / fgets / fprintf / fread
- Library state
- Buffer, position, end and error indicators
- External destination
- Terminal, file, or another supported connection
Hosted startup supplies stdin, stdout, and stderr already open. By convention, ordinary results go to stdout and diagnostics to stderr, allowing the environment to route them separately. The names do not guarantee particular devices. All examples in this unit use byte-oriented I/O; do not casually mix wide-character and byte I/O on the same oriented stream.
2. Attempt a read, then inspect its result
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int ch;
while ((ch = getchar()) != EOF) {
if (putchar(ch) == EOF) return EXIT_FAILURE;
}
if (ferror(stdin)) return EXIT_FAILURE;
if (fflush(stdout) == EOF) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
getchar returns int, not char. Successful byte input is an unsigned-char value converted to int; EOF is a negative integer constant used as a sentinel. Keep the result in int until after the test. EOF does not mean that a special visible character was stored in the file. The loop checks each input operation rather than predicting the next one with while (!feof(stdin)).
An EOF return can signal end-of-file or a read error. ferror distinguishes the error case here. Output is checked too, including a final flush, because data accepted into a library buffer can still fail to be transmitted. The checked target has int able to represent every unsigned char value; unusual targets with a narrower int value range need extra care when distinguishing converted input values from EOF.
3. Buffering separates a call from external delivery
| Mode | Useful model |
|---|---|
| Unbuffered | Characters are intended to appear as soon as possible. |
| Line buffered | Characters are intended to be transmitted as a block when a newline is encountered, subject to stream rules. |
| Fully buffered | Characters can accumulate for block transmission, for example when a buffer fills. |
Initially stderr is not fully buffered; this does not require it to be unbuffered. Standard input and output are fully buffered when the implementation can determine that they are not interactive. Avoid a universal claim that stdout is always line buffered. A newline is also not a universal request to force every output destination to physical storage.
4. Flush an output prompt before waiting
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
if (fputs("Name: ", stdout) == EOF) return EXIT_FAILURE;
if (fflush(stdout) == EOF) return EXIT_FAILURE;
char name[20];
if (fgets(name, sizeof name, stdin) == NULL) return EXIT_FAILURE;
if (fputs("Received input.\n", stdout) == EOF) return EXIT_FAILURE;
return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
The prompt has no newline, so the program explicitly calls fflush(stdout) before reading. That asks the library to deliver unwritten output to the host environment; it is not a portable guarantee of disk durability. This small example merely acknowledges a first input chunk. It does not claim that fgets always read a complete name or validated its contents; the line-input lesson handles those questions.
5. Indicators remember events
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *stream = tmpfile();
if (stream == NULL) return EXIT_FAILURE;
int ch = fgetc(stream);
assert(ch == EOF);
assert(feof(stream) != 0);
assert(ferror(stream) == 0);
clearerr(stream);
assert(feof(stream) == 0 && ferror(stream) == 0);
return fclose(stream) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
The temporary stream begins empty. Only after the failed read is its end-of-file indicator set. Indicators persist until an operation with specified clearing behavior changes them. clearerr clears both EOF and error indicators; it neither repairs the underlying problem nor changes position. Clearing an EOF indicator does not create more input. Avoid fflush(stdin): portable C does not define it as an input-discard operation.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 7.21.1–7.21.3, 7.21.5.2, 7.21.7, 7.21.10. Stable core provisions used for the C17 baseline; not the final ISO publication.
Before you move on
- A stream is a C interface to a sequence, distinct from its underlying device.
- A read result must be checked before the program treats it as a character.
- Buffering, end-of-file indicators, and error indicators have separate meanings.
Keep these ideas separate
- EOF result / End-of-file state
- A read can report EOF because of end-of-file or an error; inspect the stream indicators to distinguish them.
Why should a character read be stored in int and checked before narrowing it to char?
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
- Because int always stores exactly one visible letter.
The purpose is preserving the function’s return interface, not a universal letter representation.
- Premature conversion to char can lose information needed by the return-value check.
✓ Correct reasoning. Keep the return type and inspect the stream’s EOF/error state as the interface requires.
- EOF is an extra character stored at the end of every file.
EOF is an integer indicator used by the interface, not a required stored file character.
C17
Ready for the next idea?
Mark this chapter as read whenever you feel ready.