使用C中的fscanf()读取文件 [英] Reading file using fscanf() in C
本文介绍了使用C中的fscanf()读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从文件中读取和打印数据。结果
我写的程序如下图所示,
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;
}
在database.txt文件中包含结果
Test1的结果
TEST2乙结果
TEST3ç
the database.txt file contains
Test1 A
Test2 B
Test3 C
当我运行code,它打印
When I run the code, it prints
不认识字。
请帮我找出这个问题。
推荐答案
首先,您正在测试 FP
的两倍。所以的printf(读取文件时出错\\ n);
从来没有被执行
First of all, you're testing fp
twice. so printf("Error Reading File\n");
never gets executed.
然后输出的fscanf
,因为你正在阅读的两个值应等于 2
。
Then, the output of fscanf
should be equal to 2
since you're reading two values.
这篇关于使用C中的fscanf()读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文