关于C#:fscanf while循环永远不会运行

fscanf while-loop never runs

我正在一个项目上,我似乎无法弄清楚为什么我查找素数的功能无法运行。 本质上,我想编写代码以首先检查文本文件日志中是否有以前遇到的质数,但是无论我为包含fscanf()的while循环添加什么内容,似乎我的代码都从未输入过。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
int filePrime(int a) {
int hold = 0;
FILE *fp = fopen("primes.txt","a+");

if (fp == NULL) {
    printf("Error while opening file.");
    exit(2);
}

/*
the while loop below this block is the one with the issue.
on first run, it should skip this loop entirely, and proceed
to finding prime numbers the old-fashioned way, while populating the file.
instead, it is skipping this loop and proceeding right into generating a
new set of prime numbers and writing them to the file, even if the previous
numbers are already in the file
*/


while (fscanf(fp,"%d", &hold) == 1){
    printf("Inside scan loop.");
    if (hold >= a) {
        fclose(fp);
        return 1;
    }
    if (a % hold == 0) {
        fclose(fp);
        return 0;
    }
}

printf("Between scan and print.
"
);

for (; hold <= a; hold++) {
    if (isPrime(hold) == 1) {
        printf("Printing %d to file
"
, hold);
        fprintf(fp,"%d
"
, hold);
        if (hold == a)
            return 1;
    }
}

fclose(fp);
return 0;
}

我已经尝试了while循环测试的各种更改。
例如 != 0,!= EOF,完全消除== 1。

我只是似乎无法使我的代码使用fscanf进入循环。

非常感谢您的帮助,非常感谢您的宝贵时间。


在评论中,我问"a+"模式离开当前位置的位置?

在Mac OS X 10.11.4上,使用"a+"模式打开文件,并将读/写位置定位在文件末尾。

演示代码(aplus.c):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>

int main(void)
{
    const char source[] ="aplus.c";
    FILE *fp = fopen(source,"a+");
    if (fp == NULL)
    {
        fprintf(stderr,"Failed to open file %s
"
, source);
    }
    else
    {
        int n;
        char buffer[128];
        fseek(fp, 0L, SEEK_SET);
        while ((n = fscanf(fp,"%127s", buffer)) == 1)
            printf("[%s]
"
, buffer);
        printf("n = %d
"
, n);
        fclose(fp);
    }
    return(0);
}

如果没有fseek()n的返回值立即为-1(EOF)。
使用fseek(),可以读取数据(源代码)。

有一件事使我感到困惑:我无法在POSIX fopen()规范(或C标准)中找到信息,该信息提到了以"a+"模式打开文件后的读/写位置。显然,无论fseek()的使用是什么,写操作都将始终在末尾。

POSIX规定,对open()的调用必须对"a+"使用O_RDWR|O_CREAT|O_APPEND,而open()指定:

The file offset used to mark the current position within the file shall be set to the beginning of the file.

但是,正如chux指出的(谢谢!),C标准明确指出:

Annex J Portability issues

J.3 Implementation-defined behaviour

J.3.12 Library functions


Whether the file position indicator of an append-mode stream is initially positioned at
the beginning or end of the file (7.21.3).

因此,在C标准中允许看到的行为。

Mac OS X上fopen()的手册页显示:

  • "a+" — Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

这是标准C所允许的;尚不清楚它是否完全兼容POSIX。