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.

总结

本文详细介绍了C语言中对文件进行操作的基本步骤,包括命名文件、打开文件、读取文件、写入文件以及关闭文件。文中还涵盖了文件操作中的错误处理方法,具体介绍了ferror()perror()feof()函数的使用及其示例程序。这些内容为编写健壮的文件操作代码提供了重要的参考,帮助开发者有效处理文件操作中的各种潜在错误。

  • 15
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

新华

感谢打赏,我会继续努力原创。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值