头文件:#include <stdio.h>
ferror()用来检测文件流是否发生了错误,其原型为:
int ferror(FILE *stream);
【参数】stream为文件指针。
【返回值】若文件流出错则返回非0,否则返回0。
ferror()一般是为增强代码强健性加入的检验性程序,避免在文件操作时出现程序锁死或错误。
ferror()函数常与clearerr()函数一起使用,如果ferror(fp)发现错误,返回一个非0值,那么调用clearerr(fp)后,ferror(fp)的值变为0。
【实例】以只读方式打开一个文件,读取文件内容,检测是否出错。
- #include<iostream.h>
- #include<stdio.h>
- void main(void)
- {
- FILE* stream;
- char s[81];
- stream = fopen("fscanf.txt","w");
- if(stream == NULL)/*流为空*/
- {
- printf("the file is opeaned error!\n");
- }
- else
- {
- fprintf(stream,"%s %ld %f %c","a_string",6500,3.1415,'x');
- fseek(stream,0L,SEEK_SET);
- fscanf(stream,"%s",s);
- printf("%ld\n",ftell(stream));
- if(ferror(stream)) /*判断是否读取出错*/ {
- printf("Error form reading file.\n");
- }
- if(ferror(stream))/*清楚错误信息*/
- {
- clearerr(stream);
- printf("Error has been cleared.\n");
- }
- if(ferror(stream))/*再次检查是否还有错误信息*/
- {
- printf("Error form reading file.\n");
- }
- fclose(stream);
- }
- }
运行结果:
程序以只写方式打开一个文件,写入一部分数据, 然后使用fscanf函数读取文件流中的数据,紧接着使用ferror函数检测出错,使用dearen()函数将错误清除。
注意:有网友问关于ferror()返回非0值的含义,但是C语言标准并未对此进行说明,或者笔者没有找到。如果您有更完善的资料,请留言说明,非常感谢。