This chapter describes the standard C I/O functions. It includes the functions defined by C89 and those added by C99. The functions defined by C89 are also supported by C++, and there is no fundamental reason that you cannot use them in a C++ program when you deem it appropriate.
In C, the header associated with the I/O functions is <stdio.h>. In C++, this header is called <cstdio>. For ease of discussion, this chapter will use the C header name, but references to <stdio.h> also apply to <cstdio>.
The <stdio.h> header defines several macros and types required by the C file system. The most important type is FILE, which is used to declare a file pointer. Two other frequently used types are size_t and fpos_t. The size_t type, which is some form of unsigned integer, is the type of the result returned by sizeof. The fpos_t type defines an object that can uniquely specify each location within a file. The most commonly used macro defined by the header is EOF, which is the value that indicates end of file. Other data types and macros in <stdio.h> are described in conjunction with the functions to which they relate.
Many of the I/O functions set the built-in global integer variable errno when an error occurs. Your program can check this variable to obtain more information about the error. The values that errno may have are implementation dependent.
The C I/O system operates through streams. A stream is a logical device that is connected to an actual physical device, which is referred to as a file, when a file is opened. In the C I/O system, all streams have the same capabilities, but files may have differing qualities. For example, a disk file allows random access, but a modem does not. Thus, the C I/O system provides a level of abstraction between the programmer and the physical device. The abstraction is the stream and the device is the file. In this way, a consistent logical interface can be maintained, even though the actual physical devices may differ.
A stream is connected to a file via a call to fopen( ). Streams are operated upon through a file pointer (which is a pointer of type FILE *). In a sense, the file pointer is the glue that holds the C I/O system together.
When a C program begins execution, three predefined streams are auto- matically opened. They are stdin, stdout, and stderr, referring to standard input, standard output, and standard error, respectively. By default, these are connected to the console, but they may be redirected to any other type of device.
C99 adds the restrict qualifier to certain parameters of several functions originally defined by C89. When this is the case, the function will be shown using its C89 prototype (which is also the prototype used by C++), but the restrict-qualified parameters will be pointed out in the function’s description.