简体   繁体   中英

Infinite loop fscanf in C

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.

"%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);
}

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