Reading file using fscanf() in C

后端 未结 4 1830
迷失自我
迷失自我 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 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 
    #include 
    #include 
    
    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;
    }
    

提交回复
热议问题