当前位置: C语言 -- 标准库 -- <stdio.h> -- ferror

ferror函数


概要:
#include <stdio.h>
int ferror(FILE *stream);

描述:

该函数验证参数stream指向流的错误指示符(error indicator)。

如果先前对流操作(例如:读写数据、设置文件位置等。)失败,将会设置错误指示符。错误指示符设置后将一直存在,直至流关闭或者直至调用rewindclearerr或者freopen函数。


参数:
FILE *stream

FILE类型指针,指向一个打开的流。


返回值:

当且仅当设置了流的错误指示符时,函数返回非0值;否则函数返回0


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
/*函数ferror范例*/

#include <stdio.h>
#include <stdlib.h>

void testError(FILE *stream)
{
    if(ferror(stream))
        puts("The error indicator is set.");
    else
        puts("The error indicator is not set.");
}

int main(void)
{
    FILE *pFile;

    /*以读取模式打开文件。*/
    pFile = fopen("gch.txt", "r");
    if(!pFile)
    {
        perror("Error");
        exit(EXIT_FAILURE);
    }

    /*写入字符,设置了错误指示符。*/
    fputc('a', pFile);

    /*测试错误指示符。*/
    testError(pFile);

    /*清除错误指示符。*/
    clearerr(pFile);

    /*再次测试错误指示符。*/
    testError(pFile);

    /*关闭文件。*/
    fclose(pFile);

    return 0;
}


输出:

The error indicator is set.

The error indicator is not set.


相关内容:
feof 测试文件末尾指示符的函数。
clearerr 清除文件末尾指示符和错误指示符的函数。
perror 输出错误信息的函数。