[c] 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.

This question is related to c file readfile scanf

The answer is


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.


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.


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

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.


Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to readfile

How to read file with async/await properly? ReadFile in Base64 Nodejs How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()? How do I read a file line by line in VB Script? open read and close a file in 1 line of code Reading file using fscanf() in C Where to put a textfile I want to use in eclipse?

Examples related to scanf

How to scanf only integer? Reading numbers from a text file into an array in C How can I read an input string of unknown length? Reading in double values with scanf in c How to do scanf for single char in C printf not printing on console How to find EOF through fscanf? How to read numbers separated by space using scanf Going through a text file line by line in C What is the format specifier for unsigned short int?