Share via


Files and Streams

Files and Streams

Text and Binary Streams | Byte and Wide Streams | Controlling Streams | Stream States****

A program communicates with the target environment by reading and writing files (ordered sequences of bytes). A file can be, for example, a data set that you can read and write repeatedly (such as a disk file), a stream of bytes generated by a program (such as a pipeline), or a stream of bytes received from or sent to a peripheral device (such as the keyboard or display). The latter two are interactive files. Files are typically the principal means by which to interact with a program.

You manipulate all these kinds of files in much the same way -- by calling library functions. You include the standard header <stdio.h> to declare most of these functions.

Before you can perform many of the operations on a file, the file must be opened. Opening a file associates it with a stream, a data structure within the Standard C library that glosses over many differences among files of various kinds. The library maintains the state of each stream in an object of type FILE.

The target environment opens three files prior to program startup. You can open a file by calling the library function fopen with two arguments. The first argument is a filename, a multibyte string that the target environment uses to identify which file you want to read or write. The second argument is a C string that specifies:

  • Whether you intend to read data from the file or write data to it, or both.
  • Whether you intend to generate new contents for the file (or create a file if it did not previously exist) or leave the existing contents in place.
  • Whether writes to a file can alter existing contents or should only append bytes at the end of the file.
  • Whether you want to manipulate a text stream or a binary stream.

Once the file is successfully opened, you can determine whether the stream is byte-oriented (a byte stream) or wide-oriented (a wide stream). Wide-oriented streams are supported only with Amendment 1. A stream is initially unbound. Calling certain functions to operate on the stream makes it byte oriented, while certain other functions make it wide oriented. Once established, a stream maintains its orientation until it is closed by a call to fclose or freopen.