C语言,char类型变量不应与EOF直接比较

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main()
{
FILE *fp;
char ch;
if((fp=fopen("123.txt","r"))==NULL)
printf("file cannot open \n");
else
printf("file opened for writing \n");
while ( ( ch = fgetc(fp) ) != EOF ) // 注意,这里使用char ch,其实是不科学的,因为最后判断结束标志时,是看ch!=EOF,而EOF的值为-1,这显然和char是不能比较的。所以,某些使用,我们都定义成int ch。
fputc(ch,stdout); //这里是输出到屏幕
if(fclose(fp)!=0)
printf("file cannot be closed \n");
else
printf("file is now closed \n");
return 0;
}

posted @ 2019-02-03 22:20  格德米斯  阅读(507)  评论(0编辑  收藏  举报