Dhiraj Baurisetty
Dhiraj Baurisetty

Reputation: 21

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?

Upvotes: 1

Views: 2339

Answers (4)

P0W
P0W

Reputation: 47794

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.

Upvotes: 1

David Ranieri
David Ranieri

Reputation: 41017

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.

Upvotes: 1

BLUEPIXY
BLUEPIXY

Reputation: 40145

#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);

}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

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.

Upvotes: 1

Related Questions