Node:Cleaning Streams, Previous:Independent Channels, Up:Stream/Descriptor Precautions



Cleaning Streams

On the GNU system, you can clean up any stream with fclean:

int fclean (FILE *stream) Function
Clean up the stream stream so that its buffer is empty. If stream is doing output, force it out. If stream is doing input, give the data in the buffer back to the system, arranging to reread it.

On other systems, you can use fflush to clean a stream in most cases.

You can skip the fclean or fflush if you know the stream is already clean. A stream is clean whenever its buffer is empty. For example, an unbuffered stream is always clean. An input stream that is at end-of-file is clean. A line-buffered stream is clean when the last character output was a newline.

There is one case in which cleaning a stream is impossible on most systems. This is when the stream is doing input from a file that is not random-access. Such streams typically read ahead, and when the file is not random access, there is no way to give back the excess data already read. When an input stream reads from a random-access file, fflush does clean the stream, but leaves the file pointer at an unpredictable place; you must set the file pointer before doing any further I/O. On the GNU system, using fclean avoids both of these problems.

Closing an output-only stream also does fflush, so this is a valid way of cleaning an output stream. On the GNU system, closing an input stream does fclean.

You need not clean a stream before using its descriptor for control operations such as setting terminal modes; these operations don't affect the file position and are not affected by it. You can use any descriptor for these operations, and all channels are affected simultaneously. However, text already "output" to a stream but still buffered by the stream will be subject to the new terminal modes when subsequently flushed. To make sure "past" output is covered by the terminal settings that were in effect at the time, flush the output streams for that terminal before setting the modes. See Terminal Modes.