首页 文章

C - 程序无法正确读取文件结尾[重复]

提问于
浏览
0

这个问题在这里已有答案:

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

#include <stdio.h>
#include <stdlib.h>

int main(void) {

int pn, quantity;
float price;
pn=1;
FILE *fp;

fp=fopen("inventory.txt", "wb");
printf("This program stores a business inventory.\n");

do {
    printf("Please enter item data (part number, quantity, price): ");
    scanf("%d, %d, %f", &pn, &quantity, &price);

    if (pn==0) {
    }

    else {
        fwrite(&pn, sizeof(int), 1, fp);
        fwrite(&quantity, sizeof(int), 1, fp);
        fwrite(&price, sizeof(float), 1, fp);
    }

} while (pn!=0);

fclose(fp);
printf("Thank you. Inventory stored in file inventory.txt.\n");
return 0;

阅读计划如下:

#include <stdio.h>
#include <stdlib.h>



int main(void) {

int pn, quantity;
float price;
int a=1;
FILE *fp;
fp=fopen("inventory.txt", "rb");
printf("Below are the items in your inventory.\n");
printf("Part#\tQuantity\tItem Price\n");

while (feof(fp)==0) {

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

}

fclose(fp);
return 0;
}

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

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

我相信问题是我的同时(feof(fp)== 0),但我不太明白feof是如何工作的,我无法弄清楚如何在不使用“break”的情况下更换它 .

如何解决此重复问题?

2 回答

  • 0

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

    函数feof()测试stream指向的流的文件结束指示符,如果设置则返回非零值 .

    意思是, 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);
    }
    
  • 0

    似乎很正常 . 当读取最后一行时,最后一个字符(用于表示输入终止的“0”)尚未读取,因此,feof(fp)返回0,程序再次进入循环 .

相关问题