我需要从文件中读取并打印数据。
我写的程序如下,
#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
测试 3 C
当我运行代码时,它会打印
无法阅读。
请帮我找出问题所在。
首先,您要测试
fp
两次。所以 printf("Error Reading File\n");
永远不会被执行。
然后,
fscanf
的输出应该等于2
,因为您正在读取两个值。
scanf()
和好友返回匹配成功的输入项数量。对于您的代码,这将是两个或更少(如果匹配项少于指定的数量)。简而言之,对手册页要更加小心:
#include <stdio.h>
#include <errno.h>
#include <stdbool.h>
int main (void) {
FILE *fp = fopen ("D:\\Sample\\database.txt", "r+");
if (!fp) {
puts ("No such file\n");
return -1;
}
char item[9] = {}, status = 0;
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 {
puts ("No or partial match.\n");
}
}
puts ("\n");
if (feof (fp)) {
puts ("EOF");
}
return 0;
}
在您的代码中:
while(fscanf(fp,"%s %c",item,&status) == 1)
为什么是 1 而不是 2? scanf 函数返回读取的对象数。
fscanf
将处理 2 个参数,因此返回 2。您的 while 语句将为 false,因此永远不会显示已读取的内容,加上它只读取了 1 行,如果不在 EOF 处,则会导致您看到的结果。