Reading file using fscanf() in C

后端 未结 4 1829
迷失自我
迷失自我 2020-12-05 11:30

I need to read and print data from a file.
I wrote the program like below,

#include
#include
int main(void)
{
char item[9         


        
相关标签:
4条回答
  • 2020-12-05 11:58

    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.

    0 讨论(0)
  • 2020-12-05 11:59

    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 讨论(0)
  • 2020-12-05 12:00

    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;
    }
    
    0 讨论(0)
  • 2020-12-05 12:00

    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.

    0 讨论(0)
提交回复
热议问题