可与fputc一起使用
#include <stdio.h>
int main(void){ //当前文件保存为P7.c,此代码作用为逐字符打印自己这个文件,名字为P7.c
FILE * file;
char c;
file = fopen("P7.c", "r"); //当前文件保存的名字就是P7.c
if(!file){ //当文件打开失败是fopen返回值为NULL也就是0,为空。就是假,非假就是真。
printf("文件打开失败\n");
return 1;
}
while((c = fgetc(file)) != EOF){ //如果文件读完了fgetc会返回一个值:EOF
printf("%c", c);
}
return 0;
}
//当文件打开失败时fopen返回值为NULL也就是0,为空。就是假,非假就是真。
if(!file){ //当文件打开失败是fopen返回值为NULL也就是0,为空。就是假,非假就是真。
printf("文件打开失败\n");
return 1;
}
也可写为:
if(file == NULL){
printf("文件打开失败\n");
return 1;
}
while((c = fgetc(file)) != EOF){ //如果文件读完了fgetc会返回一个值:EOF
//EOF的值为-1 EOF == -1
printf("%c", c);
}
可读性更强的写法为:
while(1){
c=fgetc(file);
if(c == EOF){
break;
}
printf("%c", c);
}