1

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?

Community
  • 1
  • 1

4 Answers4

1

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • The feof in the while hurts my eyes... while it sort of works, it does so for all the wrong reasons. – Jens Jul 29 '13 at 12:42
  • @Jens Right, I wanted to fix the OP's code just to make it work, and left a hint on how to "beautify" it. This way it would "stick" in his mind better. – Sergey Kalinichenko Jul 29 '13 at 12:52
1

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.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1
#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);

}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • You should the check th return from sscanf, otherwise undefined behavior may occur in the printf. – Jens Jul 29 '13 at 12:45
  • sure, it had better do so Well is good. I expect implicitly that it is the correct format(I'm following the original on this matter). – BLUEPIXY Jul 29 '13 at 12:50
  • It blur the problem rather than that there is no need. – BLUEPIXY Jul 29 '13 at 13:14
1

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.

P0W
  • 46,614
  • 9
  • 72
  • 119