温馨提示×

如何用ubuntu copendir遍历目录

小樊
42
2026-09-02 14:32:05
栏目: 智能运维

在 Ubuntu(Linux)下,opendir / readdir / closedir 是 C 语言标准库(<dirent.h>)中用来遍历目录的接口。下面给你一个完整可用的示例,并解释每一步。


一、基本思路

  1. opendir(path):打开目录,返回 DIR*
  2. readdir(dir):逐个读取目录项,返回 struct dirent*
  3. closedir(dir):关闭目录
  4. 可选:用 stat() 判断是文件还是目录,实现递归遍历

二、最简单的遍历目录示例(非递归)

示例代码:list_dir.c

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

int main(int argc, char *argv[]) {
    const char *path = argc > 1 ? argv[1] : ".";
    DIR *dir = opendir(path);

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

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

    closedir(dir);
    return 0;
}

编译和运行

gcc list_dir.c -o list_dir
./list_dir /path/to/dir

三、递归遍历目录(常用)

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    if (!dir) return;

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 ||
            strcmp(entry->d_name, "..") == 0)
            continue;

        char fullpath[1024];
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        struct stat st;
        stat(fullpath, &st);

        if (S_ISDIR(st.st_mode)) {
            printf("[DIR] %s\n", fullpath);
            list_dir(fullpath);   // 递归
        } else {
            printf("[FILE] %s\n", fullpath);
        }
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    const char *path = argc > 1 ? argv[1] : ".";
    list_dir(path);
    return 0;
}

四、常见问题说明

1. . 和 .. 是什么?

  • .:当前目录
  • ..:上级目录
    遍历时一定要跳过,否则会死循环。

2. readdir 返回的是文件名,不是完整路径

需要自己拼接路径。

3. Ubuntu 下需要头文件

#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>

五、如果只是命令行遍历(不写 C)

find /path/to/dir
ls -R /path/to/dir

如果你需要:

  • ✅ 只遍历某一层
  • ✅ 过滤文件类型
  • ✅ 多线程遍历
  • ✅ C++ / Python 版本

可以告诉我,我可以直接给你对应代码。

0 踩