Search code examples
cbatch-processingfseek

Method to Batch Update on C Programming


I need to do this Batch Update on a products list. This batch update has to retrieve EVERY product from within the database and get it's "quantity in Order". This "Quantity in Order" then has to be added to the current stock:

For e.g:

Current in Stock : 100 In order: 150

After the Batch Update they have to be: Current in Stock :250 In Order: 0

I have done this method (see below) BUT when I run it, it's not updating my Stock and neither my Order.

void batchUpdate()
{
    printf ("\n\n\n\n\t\t    ********** Batch Update *******\n \n \n");

    int tempOrder;
    int tempStock;
    int tempAdding;


    if ((pfp = fopen("products.dat","r+b")) == NULL)
    {
        printf ("Error! Cannot Open Products.dat!\n");
        printf ("Returning to Main Menu\n");
        system ("PAUSE");
        orderMainMenu();
    }


        while (fread(&p,STRUCTSIZE,1,pfp) == 1)
        {
            tempOrder = p.pOrder;
            tempStock = p.pStock;
            tempAdding = tempOrder + tempStock;
            p.pOrder = 0;
            p.pStock = tempAdding;
            fwrite (&p,STRUCTSIZE,1,pfp);
        }

    fclose (pfp);
    printf ("Orders and Stock Updated!\n");
    printf ("Returning to Main Menu!\n");
    system ("PAUSE");
    orderMainMenu();

}

I tried using fseek (pfp, -STRUCTSIZE,SEEK_CUR); but that turned my program into an infinite Loop. Also when I tried to use show All products in database, they skipped my first record and just went into an infinite loop showing the last record only. I just have to end up deleting the products.dat file from the system and redo it again.

Any suggestion? I do believe that there is something wrong with the fseek().

Thanks in advance


Solution

  • Found the error, did not do an fflush (pfp); after the fwrite();

    This is the final working code;

    void batchUpdate()
    {
        printf ("\n\n\n\n\t\t    ********** Batch Update *******\n \n \n");
    
        int tempOrder;
        int tempStock;
        int tempAdding;
    
    
        if ((pfp = fopen("products.dat","r+b")) == NULL)
        {
            printf ("Error! Cannot Open Products.dat!\n");
            printf ("Returning to Main Menu\n");
            system ("PAUSE");
            orderMainMenu();
        }
    
    
            while (fread(&p,STRUCTSIZE,1,pfp) == 1)
            {
                tempOrder = p.pOrder;
                tempStock = p.pStock;
                tempAdding = tempOrder + tempStock;
                p.pOrder = 0;
                p.pStock = tempAdding;
                fseek (pfp,-STRUCTSIZE,SEEK_CUR);
                fwrite (&p,STRUCTSIZE,1,pfp);
                fflush(pfp); //THIS WAS EMITTED AND WAS CAUSING PROBLEMS
            }
    
    fclose (pfp);
    printf ("Orders and Stock Updated!\n");
    printf ("Returning to Main Menu!\n");
    system ("PAUSE");
    orderMainMenu();
    

    }