#C 语言标准库函数 perror
/*********************************************
* @brief 便捷地打印 errno 中的错误
* @param text 提示文本
********************************************/
void perror(const char* text);
说明
便捷地将 errno
中的错误信息打印到 stderr
,等价于:
fprintf(stderr, "%s: %s\n", text, strerror(errno));
参数
text
- 提示文本
返回值
无
#示例
#include <stdio.h>
int main(void) {
FILE *fp = NULL;
// 尝试打开一个不存在的文件
fp = fopen("nonexistent_file.txt", "r");
if (fp == NULL) {
// 使用 perror 便捷打印错误说明
perror("错误说明");
// 返回失败
return 1;
}
// 文件操作...
// 关闭文件
fclose(fp);
printf("文件操作成功完成\n");
return 0;
}
运行结果:
错误说明: No such file or directory
#推荐阅读
#参考标准
- C11 standard (ISO/IEC 9899:2011):
- 7.21.10.4 The perror function (p: 339)
- C99 standard (ISO/IEC 9899:1999):
- 7.19.10.4 The perror function (p: 305)
- C89/C90 standard (ISO/IEC 9899:1990):
- 4.9.10.4 The perror function