0

我有一个名为 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);
}
4

1 回答 1

0

我希望系统更新 products.dat 文件中的库存数量

但是您只是打开 products.dat 进行读取访问pfp=fopen("products.dat", "rb");

您的fwrite声明是 to ofp,它打开到另一个文件:ofp=fopen("orders.dat","ab");

该变量ofp未声明,因此至少缺少一行代码,否则将无法编译。更新:由于某种原因ofp,它已经成为全球性的,但为什么呢?尽管如此,这不应该影响功能(假设是一个线程)。

编辑:要写入和写入文件,请使用“r+b”模式打开它。您需要找到您想要更新其库存的产品,然后将当前文件位置向后移动

fseek(pfp, -sizeof(product), SEEK_CUR);

然后fwrite是新产品记录。注意 sizeof 上的 - 符号:我们正在将当前文件位置移动到我们刚刚读取的记录的开头。

于 2013-01-06T15:15:19.727 回答