cfilereadfilescanf

Reading file using fscanf() in C


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

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.


Solution

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