Reputation: 19
I'm having some problem with modifying records in a sequential access file. When I have 2 records in the file, and I update the 2nd one, it shows:
enter model code to update
RECORD UPDATED
But when I opened the file, it just shows the first record.
void edit(void){
char mcode[20]; //model code for car
char mname[20]; //name of car
int quantity; //how many of cars are in stock
float cost; //cost to make the car
float sellingprice; //price of the car
char code[20];
FILE *fp;
FILE *temp;
printf("enter model code to update:");
scanf("%s",code);
fp=fopen("stock.txt","r");
temp=fopen("temp.txt","w");
rewind(fp);
while(fscanf(fp,"%s %s %f %f %d\n",mcode,mname,&cost,&sellingprice,&quantity)==5){
fprintf(temp,"%s %s %.2f %.2f %d\n",mcode,mname,cost,sellingprice,quantity);
if (strcmp(code,mcode) == 0) {
printf("Enter quantity : ");
scanf("%d",&quantity);
fprintf(temp,"%s %s %.2f %.2f %d\n",mcode,mname,cost,sellingprice,quantity);
}
fclose(fp);
fclose(temp);
}
remove("stock.txt");
rename("temp.txt", "stock.txt");
Upvotes: 0
Views: 182
Reputation: 13533
The fclose
statements should be outside of the while loop.
Also when code = mcode, both fprintf
commands will get executed. Try this
while(fscanf(fp,"%s %s %f %f %d\n",mcode,mname,&cost,&sellingprice,&quantity)==5){
if (strcmp(code,mcode) == 0) {
printf("Enter quantity : ");
scanf("%d",&quantity);
}
fprintf(temp,"%s %s %.2f %.2f %d\n",mcode,mname,cost,sellingprice,quantity);
}
fclose(fp);
fclose(temp);
Upvotes: 2