开发者

Reading file using fscanf() in C

开发者 https://www.devze.com 2023-01-09 09:25 出处:网络
I need to read and print data from a file. I wrote the program like belo开发者_运维知识库w, #include<stdio.h>

I need to read and print data from a file.

I wrote the program like belo开发者_运维知识库w,

#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.


First of all, you're testing fp twice. so printf("Error Reading File\n"); never gets executed.

Then, the output of fscanf should be equal to 2 since you're reading two values.


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:

#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;
}


In your code:

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

why 1 and not 2? The scanf functions return the number of objects read.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消