1
votes

I am having problems with fscanf getting stuck in an infinite loop. {

char num;

FILE *filePtr;

if ((filePtr = fopen("filename.txt", "r")) == NULL)
{
    printf("File could not be opened");
}
else
{
    while (fscanf(filePtr, "%20[^ ,]", &num) != EOF)
    {
        displayFun(num);
    }

}

return 0;

The file input that I need it to read is: 0, 1, 2, 3, 16, 17, 1234, 5678, -201, 65534, 65535, 65536, -1

For some reason the code gets stuck in a loop and the first zero and wont continue on to the other numbers.

1
Your fscanf call will return 1 on success, so compare against that, not EOF. - melpomene
I'm pretty sure you can't store 20 characters in a single char. - melpomene
@Eiko That is a C++ answer. Please observe the tag system and don't close as duplicates from different languages. - 2501
@Eiko No tag, no dup. - 2501
You get an infinite loop because when it comes across the comma, scanf() returns 0, not EOF. - Jonathan Leffler

1 Answers

2
votes

"%20[^ ,]" never consumes a , or space. They stay in filePtr for the next fscanf() call. Code needs to somehow read the , and space.

As @melpomene commented, reading text as a string into a char will not work,

Recommend to read an int and , instead.

int number;
while (fscanf(filePtr, "%d,", &number) == 1) {
    displayFun(num);
}