我没有问题打开和阅读二进制文件,当我没有把它传递给一个函数。但是,在这种情况下,我将它传递给一个函数,并继续遇到问题。在函数中打开二进制文件?看代码:
void fun1 (int amount,struct inventory a[],FILE *fp);
int main()
{
tag a[10];
int amount;
int i;
FILE *fp;
fp=fopen("e:\\invent.txt","wb");
printf("How many items do you want to enter? ");
scanf("%d",&amount);
for(i=1;i<=amount;i++)
{
printf("Enter the name of the item: ");
scanf("%s",a[i].name);
printf("Enter the unit amount the item has: ");
scanf("%d",&a[i].num);
printf("Enter the unit price for the item: ");
scanf("%f",&a[i].price);
fwrite(&a[i],sizeof(a[i]),amount,fp);
}
fclose(fp);
fun1(amount,a,fp);
}
^^这是我的输入加我的函数调用^^。
我输入:
多少个项目你想进入? 2
输入项目的名称:锤
输入单元量的项具有:32
输入的单位价格的项目:11
输入项目的名称:钉子
输入单位量的项目有:43
输入单价为项目:12
void fun1 (int amount,struct inventory a[],FILE *fp)
{
int i;
fp=fopen("e:\\invent.txt","rb");
while(fread(&a[amount],sizeof(tag),amount,fp) == amount)
{
printf("\nItem\tUnit #\tPrice\n");
for(i=1;i<=amount;i++)
{
printf("\n%s\t%d\t%.2f",a[i].name,a[i].num,a[i].price);
}
}
fclose(fp);
getchar();
}
^^我的功能^^
我的输出:
项目单位#价格
锤32 11.00
锤32 11.00
项目单位#价格
锤32 11.00
指甲43 12.00
它不应该打印“锤子”两次。只有大胆的一个应该打印。如果你可以给我一个链接,或者如果你有建议,它将非常感激!
只是出于好奇,为什么你通过fp函数?它在'main'中关闭,并在'fun1'中重新打开,所以它也可以是'fun1'中的局部变量。 –
另一个需要注意的地方是,在'main'中定义'a'为'tag a [10]',但fun1想要一个'struct inventory'数组。我猜你有'typedef结构库存标签'的地方。如果今天只是有点困惑,想想几个月后会如何。为了你自己的缘故,你应该和变量和参数的类型保持一致。 –
我传递fp给函数,因为我正在做的项目需要我有一个二进制文件,我必须在函数中显示输出。我是全新的FILE I/O的东西,所以我确定我是否做得对。 – Shamrocck