【发布时间】:2016-08-27 12:33:54
【问题描述】:
我正在做一个项目,但我似乎无法弄清楚为什么我的一个查找素数的函数无法运行。本质上,我想编写代码以首先检查文本文件日志中是否存在任何先前遇到的素数,但无论我为包含 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-loop 测试的各种更改。
前任。 != 0, != EOF,完全切断 == 1。
我似乎无法让我的代码使用 fscanf 进入循环。
非常感谢您的帮助,非常感谢您的宝贵时间。
【问题讨论】:
-
primes.txt有数据吗?第一个“字段”是数字吗?你确定吗?考虑使用fgets()读取一行 - 这样您就可以打印它,然后使用sscanf()而不是fscanf()扫描它。 -
prime.txt 要么是一个全新的文件,由 fopen() 创建,要么是由 fprintf() 进一步填充代码中的整数。我还尝试使用初始素数“2”运行它,但没有任何改变。
-
if (hold == a) return 1;不会先关闭fp。 -
为什么不看看 fscanf 返回了什么。
-
"a+"模式将当前文件指针留在哪里?在文件的开头还是结尾?如果您在fscanf()循环之前执行fseek(fp, 0L, SEEK_SET),那会改变什么吗?
标签: c while-loop scanf