在 C 中使用 fscanf() 读取文件
我需要从文件中读取并打印数据。
我编写了如下程序,
#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;
}
database.txt 文件包含
测试1 A
测试2 B
Test3 C
当我运行代码时,它打印
无法阅读。
请帮我找出问题所在。
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
When I run the code, it prints
CAN NOT READ.
Please help me to find out the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
fscanf
将处理 2 个参数,因此返回 2。您的 while 语句将为 false,因此永远不会显示已读取的内容,加上它只读取了 1 行,如果不在 EOF 处,则会导致你所看到的。fscanf
will 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.首先,您要测试
fp
两次。所以printf("Error Reading File\n");
永远不会被执行。然后,
fscanf
的输出应等于2
,因为您正在读取两个值。First of all, you're testing
fp
twice. soprintf("Error Reading File\n");
never gets executed.Then, the output of
fscanf
should be equal to2
since you're reading two values.scanf()
和朋友返回成功匹配的输入项的数量。对于您的代码,这将是两个或更少(如果匹配项少于指定的数量)。简而言之,对手册页要更加小心: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:在你的代码中:
为什么是 1 而不是 2? scanf 函数返回读取的对象数。
In your code:
why 1 and not 2? The scanf functions return the number of objects read.