简体   繁体   中英

Infinite loop after reading a file using fscanf

I am using fscanf to read the input

(2,3)

(3,4)

from a file but it goes into an infinite loop whenever I run the program. The input is from a file say abc.txt which must be passed as a command line argument. The code is give below

#include<stdio.h>
#include<stdlib.h>

int main(int argc,char **argv){

    int a,b;
    FILE *fp=fopen(argv[1],"r");

    while(!feof(fp)){
        fscanf(fp,"(%d,%d)",&a,&b);
        printf("\nThe values are :%d %d\n",a,b);
    }

    fclose(fp);

}

What might be the problem?

When fscanf does not find the data that looks like what you would like to read, it does not advance the reading position, so EOF never gets reached. Check that the fscanf gives you two numbers back, and break when it does not:

while(!feof(fp)){
    if (fscanf(fp,"(%d,%d)",&a,&b) != 2) {
        break;
    }
    printf("\nThe values are :%d %d\n",a,b);
}

You can drop the feof check altogether, because the break is going to happen sooner.

Notice that stream's internal position indicator may point to the end-of-file for the next operation, but still, the end-of-file indicator may not be set until an operation attempts to read at that point.

while(fscanf(fp,"(%d,%d)\n",&a,&b) == 2){
    printf("\nThe values are :%d %d\n",a,b);
}

Will do the trick.

#include<stdio.h>
#include<stdlib.h>

int main(int argc,char **argv){
    int a,b;
    FILE *fp=fopen(argv[1],"r");
    char linebuff[32];

    while(fgets(linebuff, sizeof(linebuff), fp)){
        sscanf(linebuff,"(%d,%d)",&a,&b);
        printf("\nThe values are :%d %d\n",a,b);
    }

    fclose(fp);

}

I think all you need is '\\n'

This works for me with your code, on a sample input as yours.

 fscanf(fp,"(%d,%d)\n",&a,&b);
                    ^

But try using sscanf & fgets for such operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM