解释 C 语言错误处理函数


文件是记录的集合,或者说是硬盘上永久存储数据的地方。

文件操作

C 编程语言中的文件操作如下:

  • 命名文件
  • 打开文件
  • 从文件读取
  • 写入文件
  • 关闭文件

语法

打开文件的语法如下:

FILE *File pointer;

例如,FILE * fptr;

命名文件的语法如下:

File pointer = fopen ("File name", "mode");

例如,

fptr = fopen ("sample.txt", "r");
FILE *fp;
fp = fopen ("sample.txt", "w");

文件错误处理

一些文件错误如下:

  • 尝试读取文件末尾之外的内容。
  • 设备溢出。
  • 尝试打开无效文件。
  • 通过以不同的模式打开文件来执行无效操作。

ferror( )

它用于检测在执行读/写操作时发生的错误。

ferror() 函数的语法如下:

语法

int ferror (file pointer);

例如,

示例

FILE *fp;
if (ferror (fp))
printf ("error has occurred");

如果成功,则返回零,否则返回非零值。

程序

以下是使用 ferror() 函数的 C 程序:

#include<stdio.h>
int main(){
   FILE *fptr;
   fptr = fopen("sample.txt","r");
   if(ferror(fptr)!=0)
      printf("error occurred");
   putc('T',fptr);
   if(ferror(fptr)!=0)
      printf("error occurred");
   fclose(fptr);
   return 0;
}

输出

执行上述程序时,会产生以下结果:

error occurred
Note: try to write a file in the read mode results an error.

perror ( )

它用于打印错误。

perror() 函数的语法如下:

语法

perror (string variable);

例如,

示例

FILE *fp;
char str[30] = "Error is";
perror (str);

输出如下:

Error is: error 0

程序

以下是使用 perror() 函数的 C 程序:

#include<stdio.h>
int main ( ){
   FILE *fp;
   char str[30] = "error is";
   int i = 20;
   fp = fopen ("sample.txt", "r");
   if (fp == NULL){
      printf ("file doesnot exist");
   }
   else{
      fprintf (fp, "%d", i);
      if (ferror (fp)){
         perror (str);
         printf ("error since file is opened for reading only");
      }
   }
   fclose (fp);
   return 0;
}

输出

执行上述程序时,会产生以下结果:

error is: Bad file descriptor
error since file is opened for reading only

feof( )

它用于检查是否已到达文件末尾。

feof() 函数的语法如下:

语法

int feof (file pointer);

例如,

示例

FILE *fp;
if (feof (fp))
printf ("reached end of the file");

如果成功,则返回非零值,否则返回零。

程序

以下是使用 feof() 函数的 C 程序:

实时演示

#include<stdio.h>
main ( ){
   FILE *fp;
   int i,n;
   fp = fopen ("number. txt", "w");
   for (i=0; i<=100;i= i+10){
      putw (i, fp);
   }
   fclose (fp);
   fp = fopen ("number. txt", "r");
   printf ("file content is");
   for (i=0; i<=100; i++){
      n = getw (fp);
      if (feof (fp)){
         printf ("reached end of file");
         break;
      }else{
         printf ("%d", n);
      }
   }
   fclose (fp);
   getch ( );
}

输出

执行上述程序时,会产生以下结果:

File content is
10 20 30 40 50
60 70 80 90 100
Reached end of the file.

更新于: 2021-03-24

717 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.