Basically, I am trying to develop a customer order system. I wrote a method where the system gets the latest order placed by a particular customer. The user is asked to enter the customer id number in order to get the corresponding order. This function is not working properly because it is getting the first order placed and not the LAST one. I used fseek in my method but it is still not working.
void ViewLatestOrder()
{
order o;
char Customerid[10];
ofp=fopen("orders.dat","rb");
printf("\nEnter the Customer ID: \n");
scanf("%s",&Customerid);
rewind(ofp);
fseek(ofp, -sizeof(order), SEEK_END);
while(fread(&o,sizeof(o),1,ofp)==1 && !feof(ofp))
{
if(strcmp(Customerid,o.CustomerID)== 0)
{
printf("\n========================================================\n\n");
printf("\t\t Order Details of %s\n\n",o.CustomerID);
printf("========================================================\n\n");
printf("Product Name: %s\n",o.ProductName);
printf("Product Quantities: %d\n",o.ProductQuantities);
printf("Total Order Price: %.2f\n",o.TotalOrderPrice);
printf("========================================================\n\n");
}
else
{
fseek(ofp, -2*sizeof(order), SEEK_CUR);
}
}
OrdersSubMenu();
fclose(ofp);
}
Your code is right, you’re just failing to break out of the while loop on the first successfull find. It then continues to find and print all previous orders as well.