C ferror()

ferror() 函数定义在 stdio.h 头文件中。它有助于在给定流进行读写操作时检测错误。


int ferror(FILE *stream); #where stream should be a file pointer

 

ferror() 参数: 

ferror() 函数接受一个参数。要确定错误的具体性质,我们可以使用 perror() 方法。

参数 描述 必需/可选
stream 指向 FILE 对象的指针,用于标识流。 必需

ferror() 返回值

如果与流关联的错误指示器已设置,则 ferror() 函数返回非零值,否则返回零。

输入 返回值
如果发生错误 非零
如果没有错误

ferror() 示例

示例 1:C 语言中 ferror() 函数的工作原理?


#include <stdio.h>

int main()
{
   FILE *pnt;
   char chr;

   pnt = fopen("myfile.txt", "w");

   chr = fgetc(pnt);
   if( ferror(pnt) ) {
      printf("Reading error from file : myfile.txt\n");
   }
   clearerr(pnt);
   
   if( ferror(pnt) ) {
      printf("Reading error from file : myfile.txt\n");
   }
   fclose(pnt);

   return(0);
}

输出


Reading error from file "myfile.txt"

示例 2:C 语言中 ferror() 如何工作?


#include <stdio.h>

int main (){
    FILE *pnt;
    pnt = fopen("fileName.txt","w");
    while(!done)
    {
      putc(info, pnt);
      if(ferror(pnt))
      {
        printf("File Error..!\n");
        printf("Press any key to exit..\n");
        getch();
        exit(1);
      }
   }
}

输出


File Error..!
Press any key to exit..