爲什麼這段代碼讀取文件中的最後一個東西兩次?誰能幫我 ?? feof和循環有什麼問題? 爲什麼它總是不正確,我試了太多次?該回路有什麼問題?
在此先感謝
char n [120];
char p[120];
char e [120];
char g [120];
int no;
FILE *fptr;
fptr=fopen("answer.txt","ra+");
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
printf("%6s %-20s %-15s %-15s %-15s\n","Acct#","Name","Phone","Email","Group" );
printf("------ -------------------- ------------- ------------------- --------------- \n");
currentc=firstc;
while(!feof(fptr))
{
currentc= (struct contact *) malloc(sizeof(struct contact));
fscanf(fptr,"%d",&no);
currentc->number=no;
printf("%6d: ",currentc->number);
fscanf(fptr,"%s",&n);
strcpy(currentc->name,n);
printf("%-20s ",currentc->name);
fscanf(fptr,"%s",&p);
strcpy(currentc->phone,p);
printf("%-15s ",currentc->phone);
fscanf(fptr,"%s",&e);
strcpy(currentc->email,e);
printf("%-20s ",currentc->email);
fscanf(fptr,"%s",&g);
strcpy(currentc->group,g);
printf("%-15s ",currentc->group);
}
fclose(fptr);
}
閱讀[爲什麼是「while(!feof(file))」總是出錯?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)知道爲什麼。掃描'%s'時,不要在變量名前加'&'。並使用''r「'(read)或''r +」'(讀寫)作爲'fopen'的第二個參數。此外,[不要將'malloc'和family的結果在C中進行轉換](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) –
和format/indent你的代碼更好,它會幫助你 – Eregrith