C语言笔记(2)-文件
2016-06-17 本文已影响16人
deactivateuser
前些天在复习C语言文件操作时遇到了这样一个问题,读取文件时,文件末尾多了个/377
以下是错误代码:
#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");
//-----------这里出错-----------------
while (!feof(fp)) {
putchar(fgetc(fp));
}
//-----------------------------------
fclose(fp);
printf("\nRead successfully.\n");
}
int main(int argc, const char * argv[]) {
writeFile();
readFile();
return 0;
}
错误原因
当换种写法后找到了错误原因。
printf("EOF=%c",EOF);
输出EOF=/377
建议写法
char c;
while(1) {
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
putchar(c);
}
或
char ch;
while ((ch=fgetc(fp))!=EOF) {
putchar(ch);
}