温馨提示×

ubuntu copendir和readdir怎么配合

小樊
48
2026-09-11 14:05:58
栏目: 智能运维

在 Ubuntu(Linux)下,opendir 和 readdir 通常配合用来遍历一个目录中的所有文件和子目录。它们都来自 <dirent.h>。

下面从 基本用法 → 示例代码 → 注意事项 给你讲清楚。


一、函数作用说明

1. opendir

DIR *opendir(const char *name);
  • 打开一个目录
  • 成功返回 DIR* 指针
  • 失败返回 NULL

2. readdir

struct dirent *readdir(DIR *dirp);
  • 读取目录中的一个条目
  • 返回 struct dirent*
  • 读到末尾返回 NULL

二、配合使用的基本流程

opendir → readdir(循环) → closedir

三、完整示例(C 语言)

示例:列出当前目录下所有文件

#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;
}

编译运行:

gcc listdir.c -o listdir
./listdir

四、struct dirent 常用字段

struct dirent {
    ino_t          d_ino;
    off_t          d_off;
    unsigned short d_reclen;
    unsigned char  d_type;
    char           d_name[256];
};

常用:

  • d_name:文件名
  • d_type:
    • DT_REG 普通文件
    • DT_DIR 目录

五、只列出普通文件(示例)

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

六、过滤 . 和 ..

if (strcmp(entry->d_name, ".") == 0 ||
    strcmp(entry->d_name, "..") == 0)
    continue;

七、递归遍历子目录(思路)

if (entry->d_type == DT_DIR) {
    // 拼接路径
    // 再次 opendir + readdir
}

注意:递归时要避免死循环(如符号链接)


八、常见错误

❌ 忘记 closedir
❌ readdir 不是线程安全的(可用 readdir_r)
❌ 把 readdir 当“读文件内容”(它是读目录项)


如果你愿意,我也可以给你:

  • ✅ 递归遍历目录的完整代码
  • ✅ C++ std::filesystem 版本
  • ✅ Python / Shell 对比写法

你想看哪一种?

0 踩