前些天在復(fù)習(xí)C語(yǔ)言文件操作時(shí)遇到了這樣一個(gè)問(wèn)題檀轨,讀取文件時(shí),文件末尾多了個(gè)/377
以下是錯(cuò)誤代碼:
#include <stdio.h>
#define FILENAME "output.txt"
/**
* Write a string into a file.
*/
void writeFile(){
FILE *fp;
char ch;
if ((fp=fopen(FILENAME,"w"))==NULL) {
printf("Cannot open file.\n");
}
printf("Please input a string. (End up with '#')\n");
while ((ch=getchar())!='#') {
fputc(ch, fp);
}
fclose(fp);
printf("Write successfully.\n\n\n");
}
/**
* Read a string from a file.
*/
void readFile(){
FILE *fp;
if ((fp=fopen(FILENAME,"r"))==NULL) {
printf("Cannot open file.\n");
}
printf("Read file...\n");
//-----------這里出錯(cuò)-----------------
while (!feof(fp)) {
putchar(fgetc(fp));
}
//-----------------------------------
fclose(fp);
printf("\nRead successfully.\n");
}
int main(int argc, const char * argv[]) {
writeFile();
readFile();
return 0;
}
錯(cuò)誤原因
當(dāng)換種寫(xiě)法后找到了錯(cuò)誤原因刘绣。
printf("EOF=%c",EOF);
輸出EOF=/377
建議寫(xiě)法
char c;
while(1) {
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
putchar(c);
}
或
char ch;
while ((ch=fgetc(fp))!=EOF) {
putchar(ch);
}