APUE Chapter 5 - Standard I/O Library
5.1. Introduction
5.2. Streams and FILE Objects
With the standard I/O library, the discussion centers around streams.
Initially, when a stream is created, it has no orientation. If a multibyte I/O function is used on a stream without orientation, the stream's orientation is set to wide-oriented. If a byte I/O function is used on a stream without orientation, the stream's orientation is set to byte-oriented. Only two functions can change the orientation once set. The "freopen" function will clear a stream's orientation; the "fwide" function can be used to set a stream's orientation.
#include <stdio.h>
#include <wchar.h>
int fwide(FILE *fp, int mode); // 返回值: 若流是宽定向的则返回正值,若流是字节定向的返回负值,若流是未定向的返回0
When we open a stream, the standard I/O function fopen returns a pointer to a FILE object. This object is normally a structure that contains all the information required by the standard I/O library to manage the stream: the file descriptor used for actual I/O, a pointer to a buffer for the stream, the size of the buffer, a count of the number of characters currently in the buffer, an error flag, and the like.
Application software should never need to examine a FILE object. To reference the stream, we pass itsFILE pointer as an argument to each standard I/O function. Throughout this text, we'll refer to a pointer to a FILE object, the type FILE * as a file pointer.
5.3. Standard Input, Standard Output, and Standard Error
Three streams are predefined and automatically available to a process: standard input, standard output, and standard error. These streams refer to the same files as the file descriptors STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO. These three standard I/O streams are referenced through the predefined file pointers stdin, stdout, and stderr. The file pointers are defined in the <stdio.h> header.
5.4. Buffering
The goal of the buffering provided by the standard I/O library is to use the minimum number of read and write calls. Unfortunately, the single aspect of the standard I/O library that generates the most confusion is its buffering.
5.5. Opening a Stream
The following three functions open a standard I/O stream.
#include <stdio.h>
FILE * fopen(const char * restrict pathname, const char * restrict type); //返回值: 若成功则返回文件指针,若出错则返回NULL
FILE * freopne(const char * restrict pathname, const char * restrict type, FILE * restrict fp); //返回值: 若成功则返回文件指针,若出错则返回NULL
FILE * fdopen(int filedes, const char * type); //返回值: 若成功则返回文件指针,若出错则返回NULL
An open stream is closed by calling fclose.
#include <stdio.h>
int fclose(FILE *fp); // return: 0 if success, EOF on error
5.6. Reading and Writing a Stream
5.7. Line-at-a-Time I/O
5.8. Standard I/O Efficiency
5.9. Binary I/O