15.14 流错误函数
下面的函数用于判断流的状态:
int feof( FILE *stream );
int ferror( FILE *stream );
void clearerr( FILE *stream );
如果流当前处于文件尾,feof函数返回真。这个状态可以通过对流执行fseek、rewind或fsetpos函数来清除。ferror函数报告流的错误状态,如果出现任何读/写错误,函数就返回真。最后,clearerr函数对指定流的错误标志进行重置。
/*
** 流错误函数。
*/
#include <stdio.h>
#include <stdlib.h>
int main( void ){
FILE *input;
int result;
input = fopen( "no_existence.txt", "r" );
if( !input ){
printf( "fail to open no_existence.txt file.\n" );
perror( "no_existence.txt:" );
result = ferror( input );
printf( "the result of ferror( input ) is %d\n", result );
clearerr( input );
printf( "after clearerr( input ), result is %d\n", result );
input = fopen( "no_existence.txt", "w" );
if( !input ){
printf( "fail to create the no_existence.txt file.\n" );
perror( "no_existence.txt:" );
exit( EXIT_FAILURE );
} else{
printf( "succeed to create the no_existence.txt file.\n" );
fprintf( input, "%s %d %c\n", "xiao hong", 25, 'f' );
fprintf( input, "%s %d %c\n", "xiao shu", 26, 'm' );
fprintf( input, "%s %d %c\n", "xiao ming", 20, 'f' );
input = freopen( "no_existence.txt", "r", input );
if( !input ){
printf( "fail to open no_existence.txt file.\n" );
perror( "no_existence.txt:" );
exit( EXIT_FAILURE );
}
}
}
int ch;
while( (ch = fgetc( input )) && !feof( input ) ){
fputc( ch, stdout );
}
return EXIT_SUCCESS;
}
/* 输出:

*/