温馨提示×

怎样在ubuntu用copendir

小樊
48
2026-10-05 14:30:15
栏目: 智能运维

在 Ubuntu(Linux)下,opendir 是 C 语言 中用于打开目录的标准库函数,属于 <dirent.h>。下面从基本用法 → 编译 → 示例 → 常见注意点给你讲清楚。


一、opendir 是什么?

#include <dirent.h>

DIR *opendir(const char *name);
  • 作用:打开一个目录
  • 参数:name 是目录路径
  • 返回值:
    • 成功:返回 DIR* 指针
    • 失败:返回 NULL,并设置 errno

⚠️ opendir 只是“打开目录”,要读取内容需要用 readdir。


二、基本使用步骤

  1. opendir 打开目录
  2. readdir 读取目录项
  3. closedir 关闭目录

三、完整 C 示例(Ubuntu 可直接用)

示例:列出目录下的所有文件名

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

int main() {
    DIR *dir;
    struct dirent *entry;

    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

四、编译和运行

保存为 listdir.c,然后:

gcc listdir.c -o listdir
./listdir

五、常见错误和解决方法

1. 目录不存在

No such file or directory

✅ 检查路径是否正确

2. 权限不足

Permission denied

✅ 用 ls -ld 目录名 看权限

3. 忘记 closedir

⚠️ 会导致文件描述符泄漏


六、进阶用法

打开指定目录

opendir("/home/user/Documents");

判断是文件还是目录

#include <sys/stat.h>

struct stat st;
stat(entry->d_name, &st);
if (S_ISDIR(st.st_mode)) {
    printf("[DIR] %s\n", entry->d_name);
}

七、如果你不是写 C 程序

  • Shell:用 ls
  • Python:os.listdir() / os.scandir()
  • C++17:std::filesystem

如果你想要:

  • 递归遍历目录
  • 过滤特定文件
  • 用 C++ / Python 实现

告诉我,我可以给你对应版本。

0 踩