第 24 / 187 篇

2.8. C 中的 I/O(标准 I/O 与文件 I/O)

说明

本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C2-C_depth/IO.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。

2.8. I/O in C (Standard and File)

C 支持许多用于标准 I/O 和文件 I/O 的函数。本节讨论 C 中最常用的一些 I/O 接口。

C supports many functions for performing standard I/O as well as file I/O. In this section, we discuss some of the most commonly used interfaces for I/O in C.

2.8.1. 标准输入/输出

2.8.1. Standard Input/Output

每个运行中的程序一开始都有三个默认的 I/O 流:标准输出(stdout)、标准输入(stdin)和标准错误(stderr)。程序可以向 stdout 和 stderr 写入(打印)输出,也可以从 stdin 读入输入值。stdin 通常被定义为从键盘读取输入,而 stdout 和 stderr 输出到终端。

Every running program begins with three default I/O streams: standard out (stdout), standard in (stdin), and standard error (stderr). A program can write (print) output to stdout and stderr, and it can read input values from stdin. stdin is usually defined to read in input from the keyboard, whereas stdout and stderr output to the terminal.

C 的 stdio.h 库提供了用于打印到标准输出的 printf 函数,以及可用于从标准输入读取值的 scanf 函数。C 还有一次读写一个字符的函数(getchar 和 putchar),以及其他用于向标准 I/O 流读写字符的函数和库。C 程序必须显式包含 stdio.h 才能调用这些函数。

The C stdio.h library provides the printf function used for printing to standard out and the scanf function that can be used to read in values from standard in. C also has functions to read and write one character at a time (getchar and putchar), as well as other functions and libraries for reading and writing characters to standard I/O streams. A C program must explicitly include stdio.h to call these functions.

你可以改变运行中程序的 stdin、stdout 和/或 stderr 读取或写入的位置。一种方法是把它们中的一个或全部重定向到文件进行读写。下面是一些把程序的 stdin、stdout 或 stderr 重定向到文件的 shell 命令示例($ 是 shell 提示符):

You can change the location that a running program’s stdin, stdout and/or stderr read from or write to. One way to do this is by re-directing one or all of these to read or write to a file. Here are some example shell commands for redirecting a program’s stdin, stdout, or stderr to a file ($ is the shell prompt):

译注

&> 是 bash(和 zsh)的扩展写法,在只支持 POSIX 语法的 sh 中不可用,可移植的写法是 ./a.out > outfile.txt 2>&1。另外示例注释中写的是 out.txt,命令里实际用的是 outfile.txt。

1
2
3
4
5
6
7
8
9
10
11
12
#  redirect a.out's stdin to read from file infile.txt:
$ ./a.out < infile.txt

# redirect a.out's stdout to print to file outfile.txt:
$ ./a.out > outfile.txt

# redirect a.out's stdout and stderr to a file out.txt
$ ./a.out &> outfile.txt

# redirect all three to different files:
# (< redirects stdin, 1> stdout, and 2> stderr):
$ ./a.out < infile.txt 1> outfile.txt 2> errorfile.txt

printf

printf

C 的 printf 函数类似于 Python 中格式化的 print 调用:调用者指定一个要打印的格式字符串。格式字符串中通常含有特殊的格式说明符,包括用来打印制表符(\t)或换行符(\n)的特殊字符,或者在输出中为某个值指定占位符(% 后跟一个类型说明符)。在传给 printf 的格式字符串中加入占位符时,要在格式字符串之后把对应的值作为额外参数传入。下面是调用 printf 的一些例子:

C’s printf function resembles formatted print calls in Python, where the caller specifies a format string to print. The format string often contains special format specifiers, including special characters that will print tabs (\t) or newlines (\n), or that specify placeholders for values in the output (% followed by a type specifier). When adding placeholders in a format string passed to printf, pass their corresponding values as additional arguments following the format string. Here are some example calls to printf:

printf.c

printf.c

1
2
3
4
5
6
int x = 5, y = 10;
float pi = 3.14;

printf("x is %d and y is %d\n", x, y);

printf("%g \t %s \t %d\n", pi, "hello", y);

运行时,这些 printf 语句输出:

When run, these printf statements output:

1
2
x is 5 and y is 10
3.14 hello 10

注意第二次调用中制表符(\t)是如何打印出来的,以及不同类型的值使用的不同格式占位符(%g、%s 和 %d)。

Note how the tab characters (\t) get printed in the second call, and the different formatting placeholders for different types of values (%g, %s, and %d).

下面是常见 C 类型的一组格式占位符。注意 long 和 long long 值的占位符带有 l 或 ll 前缀。

Here’s a set of formatting placeholders for common C types. Note that placeholders for long and long long values include an l or ll prefix.

1
2
3
4
5
6
7
8
9
10
11
%f, %g: placeholders for a float or double value
%d: placeholder for a decimal value (char, short, int)
%u: placeholder for an unsigned decimal
%c: placeholder for a single character
%s: placeholder for a string value
%p: placeholder to print an address value

%ld: placeholder for a long value
%lu: placeholder for an unsigned long value
%lld: placeholder for a long long value
%llu: placeholder for an unsigned long long value

下面是它们的一些用法示例:

Here are some examples of their use:

1
2
3
4
5
6
7
8
9
10
float labs;
int midterm;

labs = 93.8;
midterm = 87;

printf("Hello %s, here are your grades so far:\n", "Tanya");
printf("\t midterm: %d (out of %d)\n", midterm, 100);
printf("\t lab ave: %f\n", labs);
printf("\t final report: %c\n", 'A');

运行时,输出如下:

When run, the output will look like this:

译注

输出中的 93.800003 不是笔误:93.8 无法用二进制浮点数精确表示,存进 float 后再按默认的 6 位小数打印,就显出了误差。第 4 章讲浮点表示时会解释原因。

1
2
3
4
Hello Tanya, here are your grades so far:
midterm: 87 (out of 100)
lab ave: 93.800003
final report: A

C 还允许在格式占位符中指定字段宽度。下面是一些例子:

C also allows you to specify the field width with format placeholders. Here are some examples:

1
2
3
4
5
%5.3f: print float value in space 5 chars wide, with 3 places beyond decimal
%20s: print the string value in a field of 20 chars wide, right justified
%-20s: print the string value in a field of 20 chars wide, left justified
%8d: print the int value in a field of 8 chars wide, right justified
%-8d: print the int value in a field of 8 chars wide, left justified

下面是一个在格式字符串的占位符中使用字段宽度说明符的较大例子:

Here’s a larger example that uses field width specifiers with placeholders in the format string:

printf_format.c

printf_format.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h> // library needed for printf

int main(void) {
float x, y;
char ch;

x = 4.50001;
y = 5.199999;
ch = 'a'; // ch stores ASCII value of 'a' (the value 97)

// .1: print x and y with single precision
printf("%.1f %.1f\n", x, y);

printf("%6.1f \t %6.1f \t %c\n", x, y, ch);

// ch+1 is 98, the ASCII value of 'b'
printf("%6.1f \t %6.1f \t %c\n", x+1, y+1, ch+1);

printf("%6.1f \t %6.1f \t %c\n", x*20, y*20, ch+2);
return 0;
}

运行时,程序输出如下:

When run, the program output looks like this:

1
2
3
4
4.5 5.2
4.5 5.2 a
5.5 6.2 b
90.0 104.0 c

注意,最后三条 printf 语句中制表符和字段宽度的使用,使输出呈现出表格的样子。

Note how the use of tabs and field width in the last three printf statements result in a tabular output.

最后,C 还定义了以不同表示形式显示值的占位符:

Finally, C defines placeholders for displaying values in different representations:

1
2
3
4
5
6
%x:     print value in hexadecimal (base 16)
%o: print value in octal (base 8)
%d: print value in signed decimal (base 10)
%u: print value in unsigned decimal (unsigned base 10)
%e: print float or double in scientific notation
(there is no formatting option to display a value in binary)

下面是一个用占位符以不同表示形式打印值的例子:

Here is an example using placeholders to print values in different representations:

1
2
3
4
5
6
7
8
int x;
char ch;

x = 26;
ch = 'A';

printf("x is %d in decimal, %x in hexadecimal and %o in octal\n", x, x, x);
printf("ch value is %d which is the ASCII value of %c\n", ch, ch);

运行时,程序输出如下:

When run, the program output looks like this:

1
2
x is 26 in decimal, 1a in hexadecimal and 32 in octal
ch value is 65 which is the ASCII value of A

scanf

scanf

scanf 函数提供了一种从 stdin 读入值(通常是用户通过键盘输入的值)并存入程序变量的方法。scanf 函数对用户输入数据的确切格式有些挑剔,这使它对格式不正确的用户输入比较敏感。

The scanf function provides one method for reading in values from stdin (usually from the user entering them via the keyboard) and storing them in program variables. The scanf function is a bit picky about the exact format in which the user enters data, which can make it sensitive to badly formed user input.

scanf 函数的参数与 printf 的类似:scanf 接收一个格式字符串,指定要读入的输入值的个数和类型,后面跟着用于存放这些值的程序变量的位置。程序通常把取地址(&)运算符与变量名结合使用,得到变量在程序内存中的位置——变量的内存地址。下面是一个读入两个值(一个 int 和一个 float)的 scanf 调用示例:

The arguments to the scanf function are similar to those of printf: scanf takes a format string that specifies the number and type of input values to read in, followed by the locations of program variables into which the values should be stored. Programs typically combine the address of (&) operator with a variable name to produce the location of the variable in the program’s memory — the memory address of the variable. Here’s an example call to scanf that reads in two values (an int and a float):

scanf_ex.c

scanf_ex.c

1
2
3
4
5
6
7
int x;
float pi;

// read in an int value followed by a float value ("%d%g")
// store the int value at the memory location of x (&x)
// store the float value at the memory location of pi (&pi)
scanf("%d%g", &x, &pi);

各个输入值之间必须至少用一个空白字符(例如空格、制表符、换行符)隔开。不过,scanf 在寻找每个数值字面量的起止位置时会跳过前后的空白字符。因此,用户输入数值 8 和 3.14 时,两个值前后可以有任意多的空白(两者之间至少有一个空白字符),scanf 总会读入 8 并赋给 x,读入 3.14 并赋给 pi。例如,下面这个两个值之间有很多空格的输入,会读入 8 存入 x,读入 3.14 存入 pi:

Individual input values must be separated by at least one whitespace character (e.g., spaces, tabs, newlines). However, scanf skips over leading and trailing whitespace characters as it finds the start and end of each numeric literal value. As a result, a user could enter the value 8 and 3.14 with any amount of whitespace before or after the two values (and at least one or more whitespace characters between), and scanf will always read in 8 and assign it to x and read in 3.14 and assign it to pi. For example, this input with lots of spaces between the two values will result in reading in 8 and storing it in x, and 3.14 and storing in pi:

1
8                   3.14

程序员为 scanf 编写的格式字符串常常只由占位说明符组成,它们之间没有其他字符。要读入上面的两个数,格式字符串可以是这样的:

Programmers often write format strings for scanf that only consist of placeholder specifiers without any other characters between them. For reading in the two numbers above, the format string might look like:

1
2
// read in an int and a float separated by at least one white space character
scanf("%d%g",&x, &pi);

getchar 与 putchar

getchar and putchar

C 函数 getchar 和 putchar 分别从 stdin 读入、向 stdout 写出单个字符值。对于需要仔细检测和处理格式错误的用户输入的 C 程序,getchar 尤其有用(scanf 在这方面并不健壮)。

The C functions getchar and putchar respectively read or write a single character value from stdin and to stdout. getchar is particularly useful in C programs that need to support careful error detection and handling of badly formed user input (scanf is not robust in this way).

1
2
ch = getchar();  // read in the next char value from stdin
putchar(ch); // write the value of ch to stdout

2.8.2. 文件输入/输出

2.8.2. File Input/Output

C 标准 I/O 库(stdio.h)提供了用于文件 I/O 的流接口。文件(file)存储的是持久数据:在创建它的程序执行结束后依然存在的数据。文本文件表示一个字符流,每个打开的文件都记录着它在字符流中的当前位置。打开文件时,当前位置从文件中的第一个字符开始,每读(或写)一个字符,当前位置就随之移动。要读取文件中的第 10 个字符,需要先读完前 9 个字符(或者用 fseek 函数显式地把当前位置移到第 10 个字符)。

The C standard I/O library (stdio.h) includes a stream interface for file I/O. A file stores persistent data: data that lives beyond the execution of the program that created it. A text file represents a stream of characters, and each open file tracks its current position in the character stream. When opening a file, the current position starts at the very first character in the file, and it moves as a result of every character read (or written) to the file. To read the 10th character in a file, the first 9 characters need to first be read (or the current position must be explicitly moved to the 10th character using the fseek function).

C 的文件接口把文件看作输入流或输出流,库函数从文件流中的下一个位置读取或向其写入。fprintf 和 fscanf 函数是 printf 和 scanf 在文件 I/O 上的对应版本。它们用格式字符串指定要写入或读取什么,并带有为写入或读取的数据提供值或存储位置的参数。类似地,库还提供了 fputc、fgetc、fputs 和 fgets 函数,用于向文件流读写单个字符或字符串。尽管 C 中有许多支持文件 I/O 的库,我们只详细介绍 stdio.h 库针对文本文件的流接口。

C’s file interface views a file as an input or output stream, and library functions read from or write to the next position in the file stream. The fprintf and fscanf functions serve as the file I/O counterparts to printf and scanf. They use a format string to specify what to write or read, and they include arguments that provide values or storage for the data that gets written or read. Similarly, the library provides the fputc, fgetc, fputs, and fgets functions for reading and writing individual characters or strings to file streams. Although there are many libraries that support file I/O in C, we only present the stdio.h library’s stream interface to text files in detail.

文本文件可能像 stdin 和 stdout 流一样含有特殊字符:换行符('\n')、制表符('\t')等。此外,读到文件数据的末尾时,C 的 I/O 库会产生一个特殊的文件结束字符(EOF),表示文件结束。从文件读取的函数可以检测 EOF,以判断是否已经到达文件流的末尾。

Text files may contain special chars like the stdin and stdout streams: newlines ('\n'), tabs ('\t'), etc. Additionally, upon reaching the end of a file’s data, C’s I/O library generates a special end-of-file character (EOF) that represents the end of the file. Functions reading from a file can test for EOF to determine when they have reached the end of the file stream.

译注

更准确的说法是:文件里并没有一个叫 EOF 的字符。EOF 是 <stdio.h> 定义的一个负整数常量(通常是 -1),读取函数在没有更多数据可读时返回它。正因为它不是任何 char 值,下文示例才要用 int 变量接收 getc 的返回值。

2.8.3. 在 C 中使用文本文件

2.8.3. Using Text Files in C

要在 C 中读写文件,按以下步骤操作:

To read or write a file in C, follow these steps:

  1. 声明一个 FILE * 变量:

    1
    2
    FILE *infile;
    FILE *outfile;

    这些声明创建了指向库所定义的 FILE * 类型的指针变量。在应用程序中不能对这些指针解引用,它们被传给 I/O 库函数时,代表一个特定的文件流。

  1. Declare a FILE * variable:

    1
    2
    FILE *infile;
    FILE *outfile;

    These declarations create pointer variables to a library-defined FILE * type. These pointers cannot be dereferenced in an application program. Instead, they refer to a specific file stream when passed to I/O library functions.

  1. 打开文件:调用 fopen,把变量与一个实际的文件流关联起来。打开文件时,模式(mode)参数决定程序是为读取("r")、写入("w")还是追加("a")而打开它:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    infile = fopen("input.txt", "r");  // relative path name of file, read mode
    if (infile == NULL) {
    printf("Error: unable to open file %s\n", "input.txt");
    exit(1);
    }

    // fopen with absolute path name of file, write mode
    outfile = fopen("/home/me/output.txt", "w");
    if (outfile == NULL) {
    printf("Error: unable to open outfile\n");
    exit(1);
    }

    fopen 函数通过返回 NULL 来报告错误,例如给它的文件名无效,或者用户没有打开指定文件的权限(比如没有对 output.txt 文件的写权限)时,就会出错。

  1. Open the file: associate the variable with an actual file stream by calling fopen. When opening a file, the mode parameter determines whether the program opens it for reading ("r"), writing ("w"), or appending ("a"):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    infile = fopen("input.txt", "r");  // relative path name of file, read mode
    if (infile == NULL) {
    printf("Error: unable to open file %s\n", "input.txt");
    exit(1);
    }

    // fopen with absolute path name of file, write mode
    outfile = fopen("/home/me/output.txt", "w");
    if (outfile == NULL) {
    printf("Error: unable to open outfile\n");
    exit(1);
    }

    The fopen function returns NULL to report errors, which may occur if it’s given an invalid filename or the user doesn’t have permission to open the specified file (e.g., not having write permissions to the output.txt file).

  1. 使用 I/O 操作来读写文件或移动文件中的当前位置:

    1
    2
    3
    4
    5
    6
    7
    int ch;  // EOF is not a char value, but is an int.
    // since all char values can be stored in int, use int for ch

    ch = getc(infile); // read next char from the infile stream
    if (ch != EOF) {
    putc(ch, outfile); // write char value to the outfile stream
    }
  1. Use I/O operations to read, write, or move the current position in the file:

    1
    2
    3
    4
    5
    6
    7
    int ch;  // EOF is not a char value, but is an int.
    // since all char values can be stored in int, use int for ch

    ch = getc(infile); // read next char from the infile stream
    if (ch != EOF) {
    putc(ch, outfile); // write char value to the outfile stream
    }
  1. 关闭文件:程序不再需要文件时,用 fclose 关闭它:

    1
    2
    fclose(infile);
    fclose(outfile);
  1. Close the file: use fclose to close the file when the program no longer needs it:

    1
    2
    fclose(infile);
    fclose(outfile);

stdio 库还提供了改变文件中当前位置的函数:

The stdio library also provides functions to change the current position in a file:

1
2
3
4
5
6
7
8
9
10
11
// to reset current position to beginning of file
void rewind(FILE *f);

rewind(infile);

// to move to a specific location in the file:
fseek(FILE *f, long offset, int whence);

fseek(f, 0, SEEK_SET); // seek to the beginning of the file
fseek(f, 3, SEEK_CUR); // seek 3 chars forward from the current position
fseek(f, -3, SEEK_END); // seek 3 chars back from the end of the file

2.8.4. stdio.h 中的标准 I/O 与文件 I/O 函数

2.8.4. Standard and File I/O Functions in stdio.h

C 的 stdio.h 库有许多函数,用于读写文件以及类似文件的标准流(stdin、stdout 和 stderr)。这些函数可以分为基于字符的、基于字符串的和格式化的 I/O 函数。下面简要介绍其中一部分函数的更多细节:

The C stdio.h library has many functions for reading and writing to files and to the standard file-like streams (stdin, stdout, and stderr). These functions can be classified into character-based, string-based, and formatted I/O functions. Briefly, here’s some additional details about a subset of these functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// ---------------
// Character Based
// ---------------

// returns the next character in the file stream (EOF is an int value)
int fgetc(FILE *f);

// writes the char value c to the file stream f
// returns the char value written
int fputc(int c, FILE *f);

// pushes the character c back onto the file stream
// at most one char (and not EOF) can be pushed back
int ungetc(int c, FILE *f);

// like fgetc and fputc but for stdin and stdout
int getchar();
int putchar(int c);

// -------------
// String Based
// -------------

// reads at most n-1 characters into the array s stopping if a newline is
// encountered, newline is included in the array which is '\0' terminated
char *fgets(char *s, int n, FILE *f);

// writes the string s (make sure '\0' terminated) to the file stream f
int fputs(char *s, FILE *f);

// ---------
// Formatted
// ---------

// writes the contents of the format string to file stream f
// (with placeholders filled in with subsequent argument values)
// returns the number of characters printed
int fprintf(FILE *f, char *format, ...);

// like fprintf but to stdout
int printf(char *format, ...);

// use fprintf to print stderr:
fprintf(stderr, "Error return value: %d\n", ret);

// read values specified in the format string from file stream f
// store the read-in values to program storage locations of types
// matching the format string
// returns number of input items converted and assigned
// or EOF on error or if EOF was reached
int fscanf(FILE *f, char *format, ...);

// like fscanf but reads from stdin
int scanf(char *format, ...);

一般来说,scanf 和 fscanf 对格式错误的输入很敏感。不过,对于文件 I/O,程序员往往可以假定输入文件格式良好,所以在这种情况下 fscanf 可能已经足够健壮。而用 scanf 时,格式错误的用户输入常常会导致程序崩溃。一次读入一个字符,并在把值转换成其他类型之前加上检查代码,会更健壮,但这需要程序员实现更复杂的 I/O 功能。

In general, scanf and fscanf are sensitive to badly formed input. However, for file I/O, often programmers can assume that an input file is well formatted, so fscanf may be robust enough in such cases. With scanf, badly formed user input will often cause a program to crash. Reading in one character at a time and including code to test values before converting them to different types is more robust, but it requires the programmer to implement more complex I/O functionality.

译注

实践中更常见的稳妥做法是:先用 fgets 读入一整行,再用 sscanf 或 strtol 之类的函数解析这一行。这样格式错误的输入最多导致这一行解析失败,而不会让输入流卡在半途。

fscanf 的格式字符串可以使用以下语法,指定不同类型的值以及从文件流读取的方式:

The format string for fscanf can include the following syntax specifying different types of values and ways of reading from the file stream:

1
2
3
4
5
6
7
8
9
10
%d integer
%f float
%lf double
%c character
%s string, up to first white space

%[...] string, up to first character not in brackets
%[0123456789] would read in digits
%[^...] string, up to first character in brackets
%[^\n] would read everything up to a newline

要写对 fscanf 的格式字符串可能很棘手,尤其是从文件中混合读取数值和字符串或字符类型时。

It can be tricky to get the fscanf format string correct, particularly when reading a mix of numeric and string or character types from a file.

下面是几个使用不同格式字符串调用 fscanf(以及一个调用 fprintf)的例子(假定前面的 fopen 调用都已成功执行):

Here are a few example calls to fscanf (and one to fprintf) with different format strings (let’s assume that the fopen calls from above have executed successfully):

译注

下面代码的最后一行只是示意:x 被声明为 int,却用 %ld(对应 long *)读取,而且 b 没有声明。实际写代码时,变量类型必须与转换说明严格匹配,-Wall 编译选项会对这类不匹配给出警告。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int x;
double d;
char c, array[MAX];

// write int & char values to file separated by colon with newline at the end
fprintf(outfile, "%d:%c\n", x, c);

// read an int & char from file where int and char are separated by a comma
fscanf(infile, "%d,%c", &x, &c);

// read a string from a file into array (stops reading at whitespace char)
fscanf(infile,"%s", array);

// read a double and a string up to 24 chars from infile
fscanf(infile, "%lf %24s", &d, array);

// read in a string consisting of only char values in the specified set (0-5)
// stops reading when...
// 20 chars have been read OR
// a character not in the set is reached OR
// the file stream reaches end-of-file (EOF)
fscanf(infile, "%20[012345]", array);

// read in a string; stop when reaching a punctuation mark from the set
fscanf(infile, "%[^.,:!;]", array);

// read in two integer values: store first in long, second in int
// then read in a char value following the int value
fscanf(infile, "%ld %d%c", &x, &b, &c);

在上面的最后一个例子中,格式字符串在一个数字之后显式地读入一个字符值,以确保文件流的当前位置被正确地推进,便于后续的 fscanf 调用。例如,这种模式常用来显式读入(并丢弃)一个空白字符(比如 ‘\n’),以确保下一次 fscanf 调用从文件的下一行开始。如果下一次 fscanf 调用要读入一个字符值,就必须多读这一个字符;否则,由于换行符没有被消耗掉,下一次 fscanf 调用会读到换行符,而不是预期的字符。如果下一次调用读入的是数值类型的值,那么 fscanf 会自动丢弃前导的空白字符,程序员就不需要显式地从文件流中读取 \n 字符。

In the final example above, the format string explicitly reads in a character value after a number to ensure that the file stream’s current position gets properly advanced for any subsequent calls to fscanf. For example, this pattern is often used to explicitly read in (and discard) a whitespace character (like ‘\n’), to ensure that the next call to fscanf begins from the next line in the file. Reading an additional character is necessary if the next call to fscanf attempts to read in a character value. Otherwise, having not consumed the newline, the next call to fscanf will read the newline rather than the intended character. If the next call reads in a numeric type value, then leading whitespace chars are automatically discarded by fscanf and the programmer does not need to explicitly read the \n character from the file stream.