开发者

Reading a FILE and using fscanf goes into an infinite loop

Here is the function that is given a FILE to scan:

void scan(FILE *file) {

    while (开发者_开发问答true) {
        char s1[1001];
        int result = fscanf(file, "%10s", s1);
        printf("%d\n", result);
        s1[1001] = '\0';
        if (result == EOF) break;
    }


}

I use fopen on file before passing it to this function. It prints out -1 in an infinite loop, but it doesn't break. How come?


You have an off-by-one error when forcing the null terminator in s1, this:

s1[1001] = '\0';

runs past the end of s1, it should be:

s1[1000] = '\0';

When you declare an array in C as char s1[X];, the X is the number of elements in the array and since C arrays are indexed starting from zero, the last element is s1[X-1].

This off-by-one could be changing the value of result between the printf and the result == EOF check.


I guess it depends on what is s1.

Make sure its a char s1[ appropriate_size ] and not char * s1.

Its working great in my case:

Reading a FILE and using fscanf goes into an infinite loop

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜