27.读文件时通过两种方式判断文件结尾
1 //判断读到文件末尾 2 #include <stdio.h> 3 #define F_PRINT_ERR(e)\ 4 do\ 5 {\ 6 if(e == NULL)\ 7 {\ 8 printf("open error");\ 9 exit(-1);\ 10 }\ 11 }\ 12 while(0) 13 int main(int argc,char* argv[]) 14 { 15 16 FILE* pf = fopen("G:/qtcode/pfw.txt","w+"); 17 F_PRINT_ERR(pf); 18 //往文件里写几个字符进去 19 char ch; 20 for(ch = 'a';ch <= 'd';ch++) 21 { 22 putchar(fputc(ch,pf)); 23 } 24 putchar(10); 25 rewind(pf); 26 //尝试通过两种方式判断读到文件末尾 27 #if 0 28 //错误用法 29 while(!feof(pf))// 30 { 31 ch = fgetc(pf); 32 printf("%x->%c\n",ch,ch); 33 } 34 #endif 35 36 #if 0 37 //正确用法,先读再判断 38 while((ch = fgetc(pf)) && (!feof(pf))) 39 { 40 printf("%x->%c\n",ch,ch); 41 } 42 #endif 43 44 #if 0 45 //正确用法,先读再判断 46 ch = fgetc(pf); 47 while(!feof(pf)) 48 { 49 printf("%x->%c\n",ch,ch); 50 ch = fgetc(pf); 51 } 52 #endif 53 54 #if 1 55 while((ch = fgetc(pf)) != EOF) 56 { 57 printf("%x->%c\n",ch,ch); 58 } 59 #endif 60 61 return 0; 62 }