YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Working with inputChapter 49 of 73

Streams, buffering, and EOF

Understand stream state, standard streams, buffering, read results, and the difference between end-of-file and an error.

5 min readIntermediateC17 baseline
Offline reading
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.

Application → stream → environment
Program interface
fgetc / fgets / fprintf / fread
Library state
Buffer, position, end and error indicators
External destination
Terminal, file, or another supported connection
The drawing shows responsibilities, not a promised physical buffer arrangement.

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

Complete C17 program
#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

ModeUseful model
UnbufferedCharacters are intended to appear as soon as possible.
Line bufferedCharacters are intended to be transmitted as a block when a newline is encountered, subject to stream rules.
Fully bufferedCharacters 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

Complete C17 program
#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

Complete C17 program
#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

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.
Explain it in your own words

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.

Why retain fgetc’s result in int until checking EOF?
Read the explanation for every choice
  1. Because int always stores exactly one visible letter.

    The purpose is preserving the function’s return interface, not a universal letter representation.

  2. 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.

  3. 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.

CHAPTER 49 / 73

In this chapter

Streams, buffering, and EOF

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping