這個問題在這里已經有了答案: 為什么“while (!feof (file))”總是錯誤的? (5 個回答) 12 小時前關閉。
背景如下:我搜索一個我想替換的 ID,然后我查看我的檔案 MedicalStore.txt 以查找它。如果我找到它,我會將它替換為檔案中以前不存在的另一行或記錄。我創建了另一個臨時檔案并復制粘貼了所有資料,除了我使用 If 條件替換的搜索 ID。我也會附上檔案。
Modify(int SiD){
struct customerinfo{
char Prefix[20];
char Name[20];
int ID;
unsigned long int Pnum;
};
struct customerinfo customer;
FILE * Fptr;
FILE * Ftemp;
Fptr = fopen("MedicalStore.txt","r");
Ftemp = fopen("replace.txt","w");
char singleLine[150],newline[150],prefix[10],name[20];
int id,c=0;
unsigned long int num;
while (!feof(Fptr)){
fgets(singleLine,150,Fptr);
c ;
sscanf(singleLine,"%s %s %d %d\n",prefix,name,&id,&num);
//printf("%s %s %d %d\n",prefix,name,id,num);
if (id == SiD){
strcpy(customer.Prefix,"Customer");
printf("Enter Customer Name:\n");
fflush(stdin);
gets(customer.Name);
printf("Enter unique ID of Customer : ");
scanf("%d",&customer.ID);
printf("Enter phone number of customer : ");
scanf("%d",&customer.Pnum);
printf("%d",customer.Pnum);
sprintf_s(newline,150, "%s %s %d %d\n",customer.Prefix,customer.Name,customer.ID,customer.Pnum);
fputs(newline,Ftemp);
} else {
fputs(singleLine,Ftemp);
}
}
fclose(Fptr);
fclose(Ftemp);
remove("MedicalStore.txt");
rename("replace.txt","MedicalStore.txt");
return 0;
}
在使用代碼進行編輯之前, 我用另一條記錄替換了第二行
uj5u.com熱心網友回復:
問題是while回圈中的條件
while (!feof(Fptr)){
fgets(singleLine,150,Fptr);
//...
該條件只能在以下呼叫之后發生fgets。所以如果fgets遇到 EOF 字串的值 singleLine沒有改變,它會保留之前輸入的資料。結果,檔案的最后一行被處理了兩次。
相反,你需要寫
while ( fgets(singleLine,150,Fptr) != NULL ) {
//...
注意這個呼叫
fflush(stdin);
有未定義的行為。
該函式gets也不安全,不受 C 標準支持。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383273.html
上一篇:對C字串陣列使用簡單的空指標
下一篇:txt檔案中的隨機值不一樣
