我在做一个项目,我似乎不明白为什么我的一个寻找素数的函数不能运行。本质上,我希望代码首先检查文本文件日志中以前遇到的素数,但是不管我为包含fscanf()的while循环放了什么,我的代码似乎永远不会进入它。
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.\n");
for (; hold <= a; hold++) {
if (isPrime(hold) == 1) {
printf("Printing %d to file\n", hold);
fprintf(fp, "%d\n", hold);
if (hold == a)
return 1;
}
}
fclose(fp);
return 0;
}
我已经尝试了while循环测试的各种更改。
例如!=0!=EOF,完全切断==1。
我似乎无法使用fscanf让代码进入循环。
非常感谢您的帮助,非常感谢您抽出时间。
最佳答案
在comment中,我问"a+"
模式离开当前位置的位置在哪里?
在Mac OS X 10.11.4上,使用"a+"
模式打开文件并将读/写位置定位在文件末尾。
演示代码(aplus.c
):
#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\n", source);
}
else
{
int n;
char buffer[128];
fseek(fp, 0L, SEEK_SET);
while ((n = fscanf(fp, "%127s", buffer)) == 1)
printf("[%s]\n", buffer);
printf("n = %d\n", n);
fclose(fp);
}
return(0);
}
如果没有
fseek()
,n
的返回值立即为-1(EOF)。使用
fseek()
,可以读取数据(源代码)。有一件事让我有点困惑:我在POSIX
fopen()
规范(或C标准)中找不到信息,该规范在打开"a+"
模式的文件后提到读/写位置。很明显,无论fseek()
的中间用途如何,写操作都将始终处于结尾。POSIX规定对
open()
的调用应使用O_RDWR|O_CREAT|O_APPEND
表示"a+"
,并且open()
指定:用于标记文件中当前位置的文件偏移量应设置为文件的开头。
但是,作为chuxnotes(谢谢!),C标准明确表示:
附件J便携性问题
J.3实施定义的行为
J.3.12图书馆职能
…
追加模式流的文件位置指示器最初是否位于
文件的开头或结尾(7.21.3)。
…
因此,在C标准中所看到的行为是允许的。
Mac OS X上
fopen()
的手册页显示:"a+"
-打开进行读写。如果文件不存在,则创建该文件。流位于文件的末尾。对文件的后续写入将始终在文件的当前结尾结束,而不考虑任何中间的fseek(3)或类似内容。这是标准C所允许的;尚不清楚它是否完全符合POSIX。