解释 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输出结果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 (string variable);
例如,
示例
FILE *fp; char str[30] = "Error is"; perror (str);
输出如下-
Error is: error 0
程序
以下是使用perror()函数的C程序-
#include输出结果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输出结果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.