使用C语言的fscanf()函数读取文件

19
我需要从文件中读取和打印数据。 我编写的程序如下:
#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包含:
Test1 A
Test2 B
Test3 C

运行代码后,输出:

无法读取。

请帮我找出问题所在。


fopen can fail for many reasons. Printing "No such file" is not useful when there is a permissions error. man perror - William Pursell
4个回答

28

首先,您对fp进行了两次测试。因此,printf("Error Reading File\n"); 永远不会被执行。

其次,fscanf 的输出应该等于2,因为您正在读取两个值。


13

scanf()及其类似函数返回成功匹配的输入项数。对于您的代码,这将是两个或更少(在指定的匹配数目不足的情况下)。简而言之,请仔细阅读手册页面:

#include <stdio.h>
#include <errno.h>
#include <stdbool.h>

int main (void) {
    FILE *fp;

    if ((fp = fopen("D:\\Sample\\database.txt", "r+")) == NULL) {
        puts("No such file\n");
        exit(1);
    }

    char item[9], status;
    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(42) 这是什么意思? - Guru
1
它相当于while(1)或伪代码中的while(true) - Michael Foukarakis

3

在你的代码中:

while(fscanf(fp,"%s %c",item,&status) == 1)  

为什么是1而不是2?scanf函数返回读取的对象数。


1

fscanf 会处理两个参数,并因此返回2。你的 while 语句将为 false,因此永远不会显示已读取的内容,而且由于它只读取了一行,如果没有到达 EOF,就会导致出现你所看到的结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接