1 函数原型 fscanf():从指定流stream读取格式化数据,函数原型如下: - int fscanf ( FILE * stream, const char * format, ... );
cstdio库描述如下: - Read formatted data from stream
- 1. Reads data from the stream and stores them according to the parameter format into the locations pointed by the additional arguments.
- 2. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.
2 参数fscanf()函数参数包括三部分: - 参数stream是fscanf()函数要读取的流,类型为FILE*;stream可以是文件流或标准输入流;当是文件流时,stream就是fopen()函数的返回值;当是标准输入流时,stream就是stdin;
- format :格式字符串,与scanf()函数一致;
- … : 可变数量的参数,与scanf()函数一致。
3 返回值fscanf()函数返回值类型为int型: - 读取成功,则返回成功读取的项数;
- 读取失败,则返回EOF。
cstdio库描述如下: - 1. On success, the function returns the number of items of the argument list successfully filled.
- 2. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.
- 3. If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.
fscanf()函数,预期读取m项,成功读取n项: [td]读取比较 | 读取状况 | 读取结果 | 返回值 | 状态设置 | n=m | 全部成功读取 | 读取成功 | 返回n | NA | 0<n<m | 部分成功读取,遇到匹配失败 | 读取成功 | 返回n | NA | 0<n<m | 部分成功读取,遇到读取错误 | 读取成功 | 返回n | 设置错误指示符(ferror) | 0<n<m | 部分成功读取,遇到文件末尾 | 读取成功 | 返回n | 设置文件结束指示符(feof) | n=0 | 未成功读取任何项,遇到匹配失败 | 读取成功 | 返回n | NA | n=0 | 未成功读取任何项,遇到读取错误 | 读取失败 | 返回EOF | 设置错误指示符(ferror) | n=0 | 未成功读取任何项,遇到文件末尾 | 读取失败 | 返回EOF | 设置文件结束指示符(feof) | 4 比较fscanf()函数和scanf()函数的工作原理类似,差异如下: - fscanf()函数从指定流stream中读取格式化数据;scanf()函数从标准输入流stdin中读取格式化数据;
- 将fscanf()函数的参数stream指定为stdin,则fscanf()函数的功能和scanf()函数的功能完全相同。
5 示例5.1 示例1使用fscanf()函数读文件并打印,示例代码如下所示: - int main()
- {
- //
- float floatData = 0.0f;
- FILE* fp = NULL;
- //
- if ((fp = fopen("1.txt", "r")) == NULL)
- {
- perror("Failed to open file ");
- exit(1);
- }
- //
- printf("scanf()函数读文件:\n");
- while (fscanf(fp, " %f", &floatData) != EOF)
- {
- printf("floatData = %f\n", floatData);
- }
- //
- fclose(fp);
- //
- printf("\n");
- //
- printf("scanf()函数读stdin:\n");
- while (fscanf(stdin, " %f", &floatData) != 0)
- {
- printf("floatData = %f\n", floatData);
- }
- //
- return 0;
- }
文件内容如下图所示: 
代码运行结果如下图所示:  5.2 示例2检查fscanf()函数成功读取的项数,示例代码如下所示: - int main()
- {
- //
- FILE* fp = NULL;
- int intData1 = 0;
- int intData2 = 0;
- int intData3 = 0;
- //
- fp = fopen("1.txt", "r");
- if (fp == NULL) {
- perror("Failed to open file ");
- exit(1);
- }
- //
- int rdItem = fscanf(fp, " %d %d %d", &intData1, &intData2, &intData3);
- printf("intData1 = %d\n", intData1);
- printf("intData2 = %d\n", intData2);
- printf("intData3 = %d\n", intData3);
- printf("成功读取项数 :%d\n", rdItem);
- //
- fclose(fp);
- //
- return 0;
- }
当文件内容为3个整数,全部成功读取,代码运行结果如下图所示: 
当文件内容为2个整数和1个字符串,部分成功读取,遇到匹配失败,代码运行结果如下图所示: 
当文件内容3个字符串,未成功读取任何项,遇到匹配失败,代码运行结果如下图所示: 
当文件内容为空,未成功读取任何项,遇到文件末尾,代码运行结果如下图所示: 
|