温馨提示×

ubuntu copendir如何遍历目录

小樊
47
2026-09-05 18:04:17
栏目: 智能运维

在 Ubuntu(Linux)下,使用 C 语言通过 opendir / readdir 遍历目录是很常见的做法。下面给你一个完整示例 + 步骤说明。


一、基本思路

  1. opendir():打开目录,返回 DIR*
  2. readdir():读取目录项,返回 struct dirent*
  3. 判断 d_type 或 stat() 区分文件和子目录
  4. closedir():关闭目录

二、简单示例(遍历当前目录)

#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

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

#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) {
        perror("opendir");
        return;
    }

    struct dirent *entry;
    char fullpath[1024];

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

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

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

        if (S_ISDIR(st.st_mode)) {
            printf("目录: %s\n", fullpath);
            list_dir(fullpath);   // 递归
        } else {
            printf("文件: %s\n", fullpath);
        }
    }

    closedir(dir);
}

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

四、常见问题

1. readdir 返回 . 和 ..

必须跳过,否则会无限递归。

2. d_type 不一定可靠

某些文件系统(如 NFS)entry->d_type == DT_UNKNOWN,需用 stat()。

3. 权限不足

遍历 /root 等目录需要 sudo。


五、相关函数速查

函数 作用
opendir 打开目录
readdir 读取目录项
closedir 关闭目录
stat 获取文件信息
S_ISDIR 判断是否为目录

如果你需要:

  • 只遍历一层
  • 按文件类型筛选
  • C++ / Python 版本
  • 多线程遍历

可以继续问我。

0 踩