我有一个名为AddOrder()的方法,用户可以在其中创建订单。当系统要求用户输入产品名称时,系统将从products.dat文件中获取特定记录。然后询问用户产品数量并确认订单。在确认订单记录时,我希望系统更新products.dat文件中的库存量,并从中减去该特定产品的产品数量。不幸的是,库存量保持不变。这是我的代码。
void addOrder()
{
FILE *pfp;
order o1;
product p;
char ProductName[100];
int found = 0;
int choice = 0;
int tmpStock = 0;
double pPrice = 0.0;
int choice2 = 0;
ofp=fopen("orders.dat","ab");
pfp=fopen("products.dat", "rb");
printf("\n========================================================\n\n");
printf("\t\t Adding an Order\n\n");
printf("========================================================\n\n");
do
{
printf("Enter CustomerID: \n");
scanf("%s",&o1.CustomerID);
}while(!findCustomer(o1.CustomerID));
printf("Enter Product Name: \n");
scanf("%s", ProductName);
while(1)
{
fread(&p,sizeof(p),1,pfp);
if(feof(pfp))
{
break;
}
if(strcmp(ProductName,p.ProductName)==0)
{
found = 1;
tmpStock = p.QuantityInStock;
pPrice = p.price;
}
}
if(found == 0)
{
printf("The Product was not found!\n");
OrdersSubMenu();
}
printf("Enter Product Quantities: \n");
scanf("%d", &o1.ProductQuantities);
if(o1.ProductQuantities > tmpStock)
{
printf("You have axeceeded available stock! Available Stock: %d\n", tmpStock);
printf("Do you want to enter product quantity again(press 1)\n");
printf("or order a different product(press 2)?\n");
scanf("%d", &choice);
if(choice == 1)
{
printf("Enter Product Quantities: \n");
scanf("%d", &o1.ProductQuantities);
}
else
if(choice == 2)
{
OrdersSubMenu();
}
}
else
{
printf("Product Quantity is available\n");
}
o1.TotalOrderPrice = o1.ProductQuantities * pPrice;
printf("Total Order Price: %.2f\n", o1.TotalOrderPrice);
printf("Do you want to confirm order? If yes press 1, if no press 2: \n");
scanf("%d", &choice2);
if(choice2 == 1)
{
fwrite(&o1,sizeof(o1),1,ofp);
}
else
if(choice2 == 2)
{
OrdersSubMenu();
}
printf("Order record was added to the system!\n");
tmpStock = tmpStock-o1.ProductQuantities;
p.QuantityInStock =tmpStock;
fclose(ofp);
fclose(pfp);
}
答案 0 :(得分:0)
我希望系统更新products.dat文件中的库存量
但您只是打开products.dat进行读取访问pfp=fopen("products.dat", "rb");
。
您的fwrite
语句是ofp
,该语句对另一个文件开放:ofp=fopen("orders.dat","ab");
未声明变量ofp
,因此至少缺少一行代码,否则无法编译。更新:出于某种原因ofp
它已成为全球性的,但为什么呢?然而,这不应该影响功能(假设一个线程)。
编辑:要写入和写入文件,请使用“r + b”模式打开它。您需要找到要更新其库存的产品,然后向后移动当前文件位置;
fseek(pfp, -sizeof(product), SEEK_CUR);
然后fwrite
新产品记录。注意 - 在sizeof上签名:我们正在将当前文件位置移动到我们刚读过的记录的开头。