标签:eof eof
c语言中文件的结尾指的是文件的最后一个字符的下一个字符
例如:文件a.txt中有三个字符abc,即文件大小为3
那么文件的实际内容如下图.
echo -n abc > a.txt
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE* fp = fopen("a.txt","r");
if(NULL==fp){
perror("fopen"),exit(-1);
}
int c;
while(!feof(fp)){
c = getc(fp);
printf("c=%d\n",c);
if(ferror(fp)){
perror("ferror"),exit(-1);
}
}
fclose(fp);
return 0;
}c=97
c=98
c=99
c=-1
上面的代码,会把文件结束符EOF也读出来(EOF是个宏,就是-1),
FILE类型中维护了两个标志,即出错标志和文件结束标志
如上,只有先读出了文件中的文件结束符EOF才能设定此文件文件结束标志
所以正确做法应该是
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE* fp = fopen("a.txt","r");
if(NULL==fp){
perror("fopen"),exit(-1);
}
int c;
while((c=getc(fp))!=EOF){
printf("c=%d\n",c);
if(ferror(fp)){
perror("ferror"),exit(-1);
}
}
return 0;
}c=97
c=98
c=99
如何读出文件最后一个字符c,如下:
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
int main(void){
FILE* fp = fopen("a.txt","r");
fseek(fp,-1,SEEK_END);
char c;
c = getc(fp);
printf("c=%d\n",c);
fseek(fp,0,SEEK_END);
printf("feof(fp)=%d\n",feof(fp));//此时在文件结尾处
//即文件最后一个字符(即c字符)的下一个字符处
//结果为0
c = getc(fp);
printf("c=%d\n",c); //c=-1
printf("feof(fp)=%d\n",feof(fp));//结果为1
return 0;
}c=99
feof(fp)=0
c=-1
feof(fp)=1
本文出自 “12208412” 博客,请务必保留此出处http://12218412.blog.51cto.com/12208412/1888412
标签:eof eof
原文地址:http://12218412.blog.51cto.com/12208412/1888412