C语言feof了解

来源:互联网 发布:怎么做好一个淘宝客 编辑:程序博客网 时间:2024/05/16 10:25

【FROM MSDN &&百科】

int feof(FILE *stream);

Tests for end-of-file on a stream.

The feof function returns a nonzero value if a read operation has attempted to read past the end of the file; it returns 0 otherwise. 

The feof routine (implemented both as a function and as a macro) determines whether the end of stream has been passed. When the end of file is passed, read operations return an end-of-file indicator until the stream is closed or until rewind, fsetpos,fseek, or clearerr is called against it.

For example, if a file contains 10 bytes and you read 10 bytes from the file,feof will return 0 because, even though the file pointer is at the end of the file, you have not attempted to read beyond the end. Only after you try to read an 11th byte will feof return a nonzero value.

feof(fp)有两个返回值:如果遇到文件结束,函数feof(fp)的值为非零值,否则为0。

EOF是文本文件结束的标志。在文本文件中,数据是以字符的ASCⅡ代码值的形式存放,普通字符的ASCⅡ代码的范围是32到127(十进制),EOF的16进制代码为0x1A(十进制为26),因此可以用EOF作为文件结束标志。

  当把数据以二进制形式存放到文件中时,就会有-1值的出现,因此不能采用EOF作为二进制文件的结束标志。为解决这一个问题,ASCI C提供一个feof函数,用来判断文件是否结束。feof函数既可用以判断二进制文件又可用以判断文本文件。

“C”语言的“feof()”函数和数据库中“eof()”函数的运做是完全不同的。数据库中“eof()”函数读取当前指针的位置,“C”语言的“feof()”函数返回的是最后一次“读操作的内容”。

DEMO1:

#include <stdio.h>#include <conio.h>int main(void){FILE *in,*out;int ch;if ((in=fopen("file_a.dat","r"))==NULL){fprintf(stderr,"cannot open inputfile\n");getch();exit(0);}if ((out=fopen("file_c.dat","w"))==NULL){fprintf(stderr,"cannot open outputfile\n");getch();exit(0);}while(1){ch=fgetc(in);if (ch == -1){break;}fprintf(stdout,"The asc of character is %c\n",ch);fputc(ch,out);}fclose(in);fclose(out);getch();return 0;}

DEMO2: 

#include <stdio.h>#include <conio.h>void file_copy(FILE *fpin,FILE *fpout);int main(){FILE *fpin;FILE *fpout;fpin=fopen("file_a.dat","r");fpout=fopen("file_b.dat","w");if (NULL==fpin){fprintf(stderr,"open file_a failed. \n");getch();return 0;}if (NULL==fpout){fprintf(stderr,"open file_b failed. \n");getch();return 0;}file_copy(fpin,fpout); fclose(fpin);fclose(fpout);getch();return 0;}/*文件拷贝*/void file_copy(FILE *fpin,FILE *fpout){char ch;int a;ch=getc(fpin);//a=feof(fpin);while(!feof(fpin)){printf("%c",ch) ;putc(ch,fpout);ch=getc(fpin);}if (feof(fpin)){printf("\n返回值是:%d\n",feof(fpin));printf("\n已复制完成,请查阅\n");} else{printf("复制失败\n");}}

 feof()可以用EOF代替吗?不可以。fgetc返回-1时,有两种情况:读到文件结尾或是读取错误。因此我们无法确信文件已经结束, 因为可能是读取错误! 这时我们需要feof()。