C语言 在 C 中使用 fscanf() 读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3351809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading file using fscanf() in C
提问by Guru
I need to read and print data from a file.
I wrote the program like below,
我需要从文件中读取和打印数据。
我写了如下程序,
#include<stdio.h>
#include<conio.h>
int main(void)
{
char item[9], status;
FILE *fp;
if( (fp = fopen("D:\Sample\database.txt", "r+")) == NULL)
{
printf("No such file\n");
exit(1);
}
if (fp == NULL)
{
printf("Error Reading File\n");
}
while(fscanf(fp,"%s %c",item,&status) == 1)
{
printf("\n%s \t %c", item,status);
}
if(feof(fp))
{
puts("EOF");
}
else
{
puts("CAN NOT READ");
}
getch();
return 0;
}
the database.txt file contains
Test1 A
Test2 B
Test3 C
database.txt 文件包含
Test1 A
Test2 B
Test3 C
When I run the code, it prints
当我运行代码时,它会打印
CAN NOT READ.
无法阅读。
Please help me to find out the problem.
请帮我找出问题所在。
回答by Hamid Nazari
First of all, you're testing fptwice. so printf("Error Reading File\n");never gets executed.
首先,你要测试fp两次。所以printf("Error Reading File\n");永远不会被执行。
Then, the output of fscanfshould be equal to 2since you're reading two values.
然后,由于您正在读取两个值,因此输出fscanf应该等于2。
回答by Michael Foukarakis
scanf()and friends return the number of input items successfully matched. For your code, that would be two or less (in case of less matches than specified). In short, be a little more careful with the manual pages:
scanf()和朋友返回匹配成功的输入项数。对于您的代码,这将是两个或更少(如果匹配少于指定)。简而言之,对手册页要多加小心:
#include <stdio.h>
#include <errno.h>
#include <stdbool.h>
int main(void)
{
char item[9], status;
FILE *fp;
if((fp = fopen("D:\Sample\database.txt", "r+")) == NULL) {
printf("No such file\n");
exit(1);
}
while (true) {
int ret = fscanf(fp, "%s %c", item, &status);
if(ret == 2)
printf("\n%s \t %c", item, status);
else if(errno != 0) {
perror("scanf:");
break;
} else if(ret == EOF) {
break;
} else {
printf("No match.\n");
}
}
printf("\n");
if(feof(fp)) {
puts("EOF");
}
return 0;
}
回答by Michael Foukarakis
In your code:
在您的代码中:
while(fscanf(fp,"%s %c",item,&status) == 1)
why 1 and not 2? The scanf functions return the number of objects read.
为什么是 1 而不是 2?scanf 函数返回读取的对象数。
回答by Didier Trosset
fscanfwill treat 2 arguments, and thus return 2. Your while statement will be false, hence never displaying what has been read, plus as it has read only 1 line, if is not at EOF, resulting in what you see.
fscanf将处理 2 个参数,因此返回 2。您的 while 语句将是假的,因此永远不会显示已读取的内容,再加上它只读取了 1 行,如果不在 EOF,导致您看到的内容。

