Gur*_*uru 15 c file scanf readfile
我需要从文件中读取和打印数据.
我写的程序如下,
#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;
}
Run Code Online (Sandbox Code Playgroud)
database.txt文件包含
Test1 A
Test2 B
Test3 C.
当我运行代码时,它会打印出来
无法阅读.
请帮我找出问题所在.
Mic*_*kis 12
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
235202 次 |
| 最近记录: |