C 语言错误代码
外观
C语言错误代码是程序运行过程中用于标识错误类型的整数值,通常通过函数返回值或全局变量(如errno
)传递。它是C语言错误处理机制的核心组成部分,帮助开发者诊断和修复问题。
概述[编辑 | 编辑源代码]
在C语言中,错误代码通常以以下形式出现:
- 函数返回值:许多标准库函数通过返回特定值(如
-1
、NULL
)表示错误。 - 全局变量
errno
:定义在<errno.h>
中,存储最近一次错误的详细代码,需配合perror()
或strerror()
使用。
常见错误代码[编辑 | 编辑源代码]
以下是errno.h
中定义的典型错误代码:
错误代码 | 宏名称 | 描述 |
---|---|---|
1 | EPERM |
操作无权限 |
2 | ENOENT |
文件或目录不存在 |
13 | EACCES |
权限不足 |
22 | EINVAL |
无效参数 |
错误代码处理示例[编辑 | 编辑源代码]
通过返回值处理错误[编辑 | 编辑源代码]
#include <stdio.h>
#include <stdlib.h>
int divide(int a, int b, int *result) {
if (b == 0) {
return -1; // 自定义错误代码
}
*result = a / b;
return 0; // 成功返回0
}
int main() {
int res;
if (divide(10, 0, &res) != 0) {
printf("错误:除数不能为0\n");
} else {
printf("结果:%d\n", res);
}
return 0;
}
输出:
错误:除数不能为0
使用errno
处理系统错误[编辑 | 编辑源代码]
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE *file = fopen("nonexistent.txt", "r");
if (file == NULL) {
printf("错误代码:%d\n", errno);
printf("错误信息:%s\n", strerror(errno));
}
return 0;
}
输出(假设文件不存在):
错误代码:2 错误信息:No such file or directory
实际应用场景[编辑 | 编辑源代码]
案例:文件操作错误处理[编辑 | 编辑源代码]
以下代码演示如何结合errno
和自定义错误代码:
#include <stdio.h>
#include <errno.h>
#define ERROR_CUSTOM_FILE -100
int read_file(const char *filename) {
FILE *file = fopen(filename, "r");
if (!file) {
if (errno == ENOENT) {
return ERROR_CUSTOM_FILE; // 自定义文件不存在错误
}
return errno; // 返回系统错误代码
}
// 文件处理逻辑...
fclose(file);
return 0;
}
高级主题[编辑 | 编辑源代码]
错误代码分类[编辑 | 编辑源代码]
数学公式表示错误码范围[编辑 | 编辑源代码]
标准错误代码通常满足:
最佳实践[编辑 | 编辑源代码]
- 始终检查可能失败的函数返回值
- 使用
perror()
快速输出可读错误信息 - 自定义错误代码时应避开系统保留值(通常>255)