#include <errno.h> // extern int errno; #include <string.h> // char *strerror(int errnum);
| errno | 宏定義 | 含義 |
|---|---|---|
| 0 | - | Success |
| 1 | EPERM | Operation not permitted |
| 2 | ENOENT | No such file or directory |
| 13 | EACCES | Permission denied |
| 21 | EISDIR | Is a directory |
| 24 | EMFILE | Too many open files |
| 28 | ENOSPC | No space left on device |
| 32 | EPIPE | Broken pipe |
完整列表可運行以下代碼自動生成:
for (int i = 0; i < 134; i++)
printf("%3d: %s\n", i, strerror(i));
int fd = open("file.txt", O_RDONLY);
if (fd == -1) {
fprintf(stderr, "[%s:%d] open failed: %s (errno=%d)\n",
__FILE__, __LINE__, strerror(errno), errno);
return -1;
}
#define CHECK_SYS(call) do { \
if ((call) == -1) { \
fprintf(stderr, "[%s:%d] %s failed: %s\n", \
__FILE__, __LINE__, #call, strerror(errno)); \
exit(EXIT_FAILURE); \
} \
} while(0)
// 使用
CHECK_SYS(fd = open("a.txt", O_RDONLY));
CHECK_SYS(n = read(fd, buf, sizeof(buf)));
errno 為線程局部變量,多線程安全。errno,成功調用不保證 errno 為 0。perror("msg") 等價於 fprintf(stderr, "msg: %s\n", strerror(errno))。