【发布时间】:2018-05-08 22:58:12
【问题描述】:
我最近一直在尝试编写一个文件写入程序,该程序可以保存零件编号、数量和零件价格的库存统计信息。在写入我的二进制文件时,我的 scanf 保存了我的价格,但是当我在下一个程序中读取它们时,它会出现大量无意义的数字,这不是我输入的。 编写程序的编译器:(* * 是用户输入)
This program stores a business inventory.
Please enter item data (part number, quantity, price): *2, 3, 1.6*
Please enter item data (part number, quantity, price): *3, 1, 5.3*
Please enter item data (part number, quantity, price): *0*
Thank you. Inventory stored in file inventory.txt
编写程序代码
#include <stdio.h>
#include <stdlib.h>
int main(int argc, int argv[])
{
int pnum=1, quantity;
float price;
FILE *fp1;
fp1 = fopen("inventory.txt", "wb+");
if(fp1 == NULL)
{
printf("Can't open!\n");
exit(EXIT_FAILURE);
}
printf("This program stores a business inventory.\n");
while(pnum != 0)
{
printf("Please enter item data (part number, quantity, price): ");
scanf("%d, %d, %f", &pnum, &quantity, &price);
printf("%d, %d, %f", pnum, quantity, price);
fwrite(&pnum, sizeof(int), 1, fp1);// Is there a way to combine these 3 fwrites into 1?
fwrite(&quantity, sizeof(int), 1, fp1);
fwrite(&price, sizeof(float), 1, fp1);
}
printf("Thank you. Inventory stored in file inventory.txt");
fclose(fp1);
return 0;
}
带有读取程序的编译器(* * 是用户输入)
Below are the items in your inventory.
Part# Quantity Item Price
2 3 1070386381?
3 1 1084856730?
0? 1 1084856730?
读取程序代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int pnum, quantity;
float price;
FILE *fp1 = fopen("inventory.txt", "rb");
if(fp1 == NULL)
{
printf("Can't open!");
exit(EXIT_FAILURE);
}
printf("Below are the items in your inventory.\n");
printf("Part#\tQuantity\t Item Price\n");
while (fread(&pnum, sizeof(int), 1, fp1) == 1)//Is there a way to combine these 3 freads into 1 line of code?
{
printf("%5d\t", pnum);
}
while (fread(&quantity, sizeof(int), 1, fp1) == 1)
{
printf("%8d\t", quantity);
}
while (fread(&price, sizeof(float), 1, fp1) == 1)
{
printf("$");
printf("%9.2f\n", price);
}
fclose(fp1);
return 0;
}
如您所见,scanf 是 scanf 并且必须与我的浮动有关,但我无法弄清楚如何修复它,因为没有 scanf 什么都不会保存到我的 inventory.txt 文件(我没有包含 .txt 文件,因为它是二进制文件),并且由于某种原因,当我输入 0 以中断循环时,它会将 0 保存在文件中。如果需要任何其他信息,我可以提供,但我想我已经提供了一切。感谢您的帮助,祝您编码愉快:)
【问题讨论】:
-
我看不到“读取程序”如何生成该输出。第一个
while循环将消耗整个文件,并在一行上打印所有数字。 -
我在读取的 printfs 中添加了 /t,因为打印时数量和价格结合在一起(没有空格),所以它看起来像 31070386381。你是说我的第一个'while' fread for pnum?跨度>
-
这确定了问题,但另一方面修复它,我不太明白如何修复它,我对文件 IO 仍然有点绿色
-
你按这个顺序写东西:pnum, qty, price, pnum, qty, price, pnum, qty, price。然后您按以下顺序阅读它们:pnum,pnum,pnum,pnum,pnum,pnum,pnum,pnum,pnum。您需要按照编写它们的顺序阅读它们。
-
“读取程序”需要一个包含三个
fread的while循环。
标签: c file-io while-loop