clearerr() 函数在 stdio.h 头文件中定义。它有助于重置由指定流指向的流相关的 End of File (EOF) 指示符和错误标志。
int fclose(FILE *stream); #where stream should be a file pointer
clearerr() 函数接受一个参数。使用 perror() 函数,我们可以找出错误的具体性质。函数显示的消息是实际错误。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| stream | 指向标识流的 FILE 对象的指针 | 必需 |
如果传入了无效流,clearerr() 函数的返回值应为 -1 并将 errno 设置为 EBADF。
| 输入 | 返回值 |
|---|---|
| 无效流 | 返回 -1 |
#include <stdio.h>
int main()
{
FILE *pnt;
char ch;
pnt = fopen("file.txt", "w");
ch = fgetc(pnt);
if( ferror(pnt) ) {
printf("Reading error from the file : file.txt\n");
}
clearerr(pnt);
if( ferror(pnt) ) {
printf("Reading error from the file : file.txt\n");
}
fclose(pnt);
return(0);
}
输出
Reading error from the file "file.txt"
#include <stdio.h>
int main (){
FILE * pnt;
pnt = fopen("testfile.txt","r");
if (pnt==NULL) perror ("Error in opening file");
else {
fputc ('x',pnt);
if (ferror (pnt)) {
printf ("Error in writing to testfile.txt\n");
clearerr (pnt);
}
fgetc (pnt);
if (!ferror (pnt))
printf ("No errors in reading testfile.txt\n");
fclose (pnt);
}
return 0;
}
输出
Error in writing to testfile.txt No errors in reading testfile.txt