gpt4 book ai didi

c - fscanf while-loop 从不运行

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:28 32 4
gpt4 key购买 nike

我正在做一个项目,但我似乎无法弄清楚为什么我的一段查找素数的函数无法运行。本质上,我想编写代码以首先检查文本文件日志中是否有任何以前遇到的素数,但无论我为包含 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() "a+" 应使用O_RDWR|O_CREAT|O_APPENDopen() 指定:

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

然而,作为chux notes (谢谢!),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。

关于c - fscanf while-loop 从不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36987613/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com