温馨提示×

ubuntu copendir错误码怎么看

小樊
43
2026-10-11 12:38:00
栏目: 智能运维

在 Ubuntu(Linux)下,opendir() 是 C 标准库里用来打开目录的函数,定义在 <dirent.h> 中。

1. 基本用法

#include <dirent.h>
#include <stdio.h>
#include <errno.h>

DIR *dir = opendir("/some/path");
if (dir == NULL) {
    perror("opendir");
    printf("errno = %d\n", errno);
}
  • opendir() 失败返回 NULL
  • 失败原因通过 全局变量 errno 表示
  • 可用 perror() 或 strerror(errno) 查看可读错误信息

2. 常见错误码(errno)

errno 值 宏名 含义
2 ENOENT 目录不存在
13 EACCES 权限不足
20 ENOTDIR 路径不是目录
24 EMFILE 进程打开文件数过多
23 ENFILE 系统打开文件数过多
12 ENOMEM 内存不足
40 ELOOP 符号链接循环

3. 查看错误码的几种方式

✅ 方式一:perror()(最常用)

perror("opendir");

输出示例:

opendir: No such file or directory

✅ 方式二:strerror()

#include <string.h>
printf("error: %s\n", strerror(errno));

✅ 方式三:直接查看 errno 数值

cat /usr/include/asm-generic/errno-base.h

或:

errno 2

4. 调试技巧

  • 确认路径是否存在:
ls -ld /some/path
  • 确认权限:
namei -l /some/path
  • 在 gdb 中查看:
p errno

5. 简单示例

#include <dirent.h>
#include <stdio.h>
#include <errno.h>

int main() {
    DIR *d = opendir("/root");
    if (!d) {
        perror("opendir");
    }
    return 0;
}

如果你有具体的错误码或报错信息,可以贴出来,我可以帮你精准分析。

0 踩