I have no problem opening and reading a binary file when i am not passing it to a function. But, in this case i am passing it to a function and keep running into a problem.
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);
}
^^This is my input plus my function call^^.
My Input:
How many items do you want to enter? 2
Enter the name of the item:Hammer
Enter the unit amount the item has: 32
Enter the unit price for the item: 11
Enter the name of the item: Nails
Enter the unit amount the item has:43
Enter the unit price for the item: 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();
}
^^My Function^^
My Output:
Item Unit # Price
Hammer 32 11.00
Hammer 32 11.00
Item Unit # Price
Hammer 32 11.00
Nails 43 12.00
It should not be printing "Hammer" twice. Only the bold one should be printed. If you can give me a link or if you have advice it would be so greatly appreciated!