C stdio buffers: what is the purpose of fflush? Choose the best description of how fflush operates on streams.

Difficulty: Medium

Correct Answer: flushes all streams and specified streams.

Explanation:


Introduction / Context:
fflush ensures that buffered output is physically written to its destination. The exact scope depends on the argument passed to the function per ISO C and common extensions.


Given Data / Assumptions:

  • We are dealing with text or binary output streams from <stdio.h>.
  • Some systems support the extension fflush(NULL) to flush all open output streams.


Concept / Approach:

int fflush(FILE *stream) flushes buffered output for the specified stream when stream is non-NULL. Many implementations also define that fflush(NULL) flushes all open output streams. Input streams are not affected by flushing in standard C (except where system-specific behavior exists).


Step-by-Step Solution:

1) If stream != NULL ⇒ write unwritten output bytes to the underlying file or device. 2) If stream == NULL (where supported) ⇒ flush all open output streams. 3) Return 0 on success; EOF on error.


Verification / Alternative check:

Testing with buffered stdout shows that fflush(stdout) forces immediate display; calling fflush(NULL) (where available) flushes all outputs, useful before abnormal termination.


Why Other Options Are Wrong:

flushes only specified stream: Incomplete because many systems also support flushing all streams via NULL.

flushes input/output buffer and flushes file buffer: Vague and do not capture the argument-based behavior.


Common Pitfalls:

  • Assuming input buffers are flushed by fflush—the standard does not require that.
  • Expecting flushing to fix logical errors such as missing newlines.


Final Answer:

flushes all streams and specified streams.

More Questions from Library Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion