我在修改顺序访问文件中的记录方面遇到了一些问题。当我在文件中有2条记录,并且我更新第二条记录时,它会显示:
enter model code to update
RECORD UPDATED
但是当我打开文件时,它只显示第一条记录。
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");
答案 0 :(得分:2)
fclose
语句应该在while循环之外。
同样,当code = mcode时,两个fprintf
命令都将被执行。试试这个
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);