I have recently been trying to write a file writing program that saves inventory statistics of part number, the quantity and a price for the part. While writing to my binary file my scanf saves my prices, but when I read them in my next program, it comes out with a slew of meaningless numbers, that are not what I input. Compiler with write program:(* * is user input)
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
Write Program Code
#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;
}
Compiler with read program (* * is user input)
Below are the items in your inventory.
Part# Quantity Item Price
2 3 1070386381?
3 1 1084856730?
0? 1 1084856730?
Read Program Code
#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;
}
As you may of seen, scanf is being scanf and must have to do with my float, but I haven't been able to figure out how to fix it, because without scanf nothing gets saved to my inventory.txt file (I didn't include the .txt file because it's binary), and for some reason when I type in 0 to break the loop, it saves the 0 in the file. If any other info is needed I can supply it, but I think I've supplied everything. Thank you for any help, and happy coding :)