C 语言提供了 perror() 和 strerror() 函数来显示与 errno 相关的文本消息。
errno:保存错误号
perror():打印错误信息:
函数原型:
extern void perror (const char *__s);
strerror():根据错误号打印错误信息
函数原型:
extern char *strerror (int __errnum);
例如:
#include <stdio.h>
#include<string.h>
#include<errno.h>
int main(int argc, char const *argv[])
{
FILE *fd = fopen("100.txt","rb"); //打开一个不存在的文件
if(NULL == fd)
{
printf("错误号: %d\n", errno);
perror("通过 perror 输出错误");
printf("通过错误号显示错误: %s\n", strerror(errno));
}
return 0;
}
使用 fopen 打开一个不存在的文件可以用 perror 作错误处理:打印如下:
但是我们一般在打印错误信息时推荐使用错误输出流 stderr 作为输出:
fprintf(stderr,"错误号: %d\n", errno);
perror("通过 perror 输出错误");
fprintf(stderr,"通过错误号显示错误: %s\n", strerror(errno));
输出结果和前面方式一样,不过更能体现程序的意义。