Ch 5 Standard I/O stdio.h

Ch 5 Standard I/O stdio.h

Buffer allocation optimizes block length for I/O operations, making users no longer need to worry about how to choose the correct block length.

When a file is opened or created using the standard I/O library, we associate a stream with a file.

Stream orientation: determines whether the stream reads/writes single-byte or multi-byte character sets. An initial stream has no orientation. If multi-character I/O functions are used, it automatically becomes multi-character oriented; similarly for single-character functions.

freopen can clear orientation, and fwide can set stream orientation. Standard input, output, and error output are three typical predefined streams.

Standard Library Buffering

The purpose of providing adaptive buffering is to reduce the number of read and write operations.

  1. Full buffering: I/O operations occur only when the buffer is full. Generally, files on disk implement full buffering. Use flush to write buffer contents (possibly not full) to disk.
  2. Line buffering: I/O operations execute when encountering newlines (or when buffer is full). Terminals typically use line buffering. Reading from an unbuffered stream requires getting data from the kernel.
  3. Unbuffered: makes information display faster. The standard error stream is unbuffered.

Standards specify: Standard error is unbuffered; if pointing to terminal devices, it uses line buffering. Otherwise, full buffering is used.

If standard I/O buffers of automatic variable type are allocated within a function, the library will automatically release the buffer when closing the stream.

Reading and Writing Streams

Read/Write operations:

  • Character-by-character I/O
  • Line-by-line I/O
  • Direct I/O: reading/writing objects, structures

fgets and fputs must handle newlines themselves.

Formatted I/O

Output

  • printf to standard output
  • fprintf writes to specified stream
  • dprintf writes to specified descriptor
  • sprintf sends formatted characters to buffer array but may overflow
  • snprintf truncates subsequent characters if exceeding buffer size

Input

  • scanf
  • fscanf
  • sscanf

Temporary Files

Implementation of tmpfile: First calls tmpnam to generate a unique path name, then creates a file with that path and immediately unlinks it. This way, when the program exits and closes the file, its contents are deleted, achieving the purpose of temporary file usage.

Memory Streams

Some standard I/O streams do not correspond to opened disk files. All operations exchange data with buffers in memory. These streams are called memory streams.

Since buffers grow automatically, buffer overflow is avoided. Memory streams are very suitable for creating strings and perform better than temporary files.