gpt4 book ai didi

C--程序未正确读取文件结尾

转载 作者:行者123 更新时间:2023-11-30 16:24:10 24 4
gpt4 key购买 nike

我正在尝试制作一组​​基本程序,其中一个程序要求用户提供一组值,该程序将其写入文件中,另一个程序从文件中读取值并将其打印到屏幕上。这是我的代码:

读取程序如下:

当我运行这两个程序时,第一个程序成功写入“inventory.txt”,但读取函数复制了最后一组值。它看起来像这样:

Please enter item data (part number, quantity, price): 3, 1, 3.0
Please enter item data (part number, quantity, price): 0

Below are the items in your inventory.
Part# Quantity Item Price
3 1 $ 3.00
3 1 $ 3.00

我相信问题出在我的 while (feof(fp)==0) 上,但我不太明白 feof 是如何工作的,而且我不知道如何在不使用“break;”的情况下替换它

如何解决此重复问题?

最佳答案

明显重复的行背后的原因是 feof() 行为。 man

The function feof() tests the end-of-file indicator for the stream pointed to by stream, returning nonzero if it is set.

意思是,feof()测试是否已设置EOF标志。到达文件末尾,但不超过它,不会设置标志。因此,执行另一次迭代,设置 EOF 标志,而不更改变量值,给人以重复的印象。

您可以更改逻辑并使用fgets(),或者将程序更改为类似的内容

int eof;
do {
eof = fread(&pn, sizeof(int), 1, fp) < 1;
if ( !eof ) {
fread(&quantity, sizeof(int), 1, fp);
fread(&price, sizeof(float), 1, fp);
printf("%5d\t%8d\t$ %9.2f\n", pn, quantity, price);
}
} while ( !eof );

或者,打火机

while ( 1 ) {  
if ( fread(&pn, sizeof(int), 1, fp) < 1 ) break;
fread(&quantity, sizeof(int), 1, fp);
fread(&price, sizeof(float), 1, fp);
printf("%5d\t%8d\t$ %9.2f\n", pn, quantity, price);
}

关于C--程序未正确读取文件结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53699420/

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