温馨提示×

debian中copendir如何遍历

小樊
45
2026-09-19 03:30:14
栏目: 智能运维

在 Debian(以及其它 Linux 系统)里,opendir 本身只是“打开目录”,真正“遍历目录”需要配合 readdir / closedir 使用。下面给你一个完整、可运行、常见的用法示例。


一、基本流程

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

DIR *dir = opendir(path);   // 打开目录
if (!dir) { perror("opendir"); return; }

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

closedir(dir);              // 关闭目录

二、完整示例(遍历当前目录)

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

int main(void)
{
    DIR *dir = opendir(".");
    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 listdir.c -o listdir
./listdir

三、递归遍历目录(常见需求)

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.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 full[1024];
        snprintf(full, sizeof(full), "%s/%s", path, entry->d_name);
        printf("%s\n", full);

        struct stat st;
        if (stat(full, &st) == 0 && S_ISDIR(st.st_mode)) {
            list_dir(full);  // 递归
        }
    }
    closedir(dir);
}

int main(void)
{
    list_dir(".");
    return 0;
}

四、常见问题

1. opendir 返回 NULL?

通常是:

  • 路径不存在
  • 权限不足

用 perror("opendir") 看原因。


2. readdir 返回的内容

struct dirent 中常用字段:

entry->d_name   // 文件名
entry->d_type   // 文件类型(DT_DIR / DT_REG 等)

3. 隐藏文件

. 和 .. 也会遍历到,需要手动跳过。


五、如果你用的是 C++

可以用 <filesystem>(C++17):

#include <filesystem>
namespace fs = std::filesystem;

for (auto &p : fs::directory_iterator("."))
    std::cout << p.path() << "\n";

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

  • ✅ 只遍历文件/目录
  • ✅ 按时间/大小排序
  • ✅ 多线程遍历
  • ✅ 用 getdents 更高效的方式

只要告诉我你的使用场景。

0 踩