温馨提示×

ubuntu copendir怎样获取子目录

小樊
32
2026-09-05 18:08:15
栏目: 智能运维

在 Ubuntu(Linux)下使用 C 语言通过 opendir / readdir 获取子目录,核心思路是:

  1. opendir 打开目录
  2. readdir 遍历目录项
  3. 通过 d_typestat 判断是否为目录
  4. 排除 ...

基本示例(使用 d_type

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

int main(int argc, char *argv[]) {
    const char *path = ".";  // 当前目录
    DIR *dir = opendir(path);
    if (!dir) {
        perror("opendir");
        return 1;
    }

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

        // DT_DIR 表示目录
        if (entry->d_type == DT_DIR) {
            printf("子目录: %s\n", entry->d_name);
        }
    }

    closedir(dir);
    return 0;
}

更可靠的方式(使用 stat

d_type 在某些情况下可能返回 DT_UNKNOWN(如某些文件系统),更稳妥的是用 stat

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

int main() {
    const char *path = ".";
    DIR *dir = opendir(path);
    if (!dir) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    char fullpath[1024];
    struct stat st;

    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);

        if (stat(fullpath, &st) == 0 && S_ISDIR(st.st_mode)) {
            printf("子目录: %s\n", entry->d_name);
        }
    }

    closedir(dir);
    return 0;
}

递归获取所有子目录(简单示例)

如果你需要递归遍历子目录

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    if (!dir) 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;
        if (stat(fullpath, &st) == 0 && S_ISDIR(st.st_mode)) {
            printf("目录: %s\n", fullpath);
            list_dir(fullpath);  // 递归
        }
    }
    closedir(dir);
}

总结

  • opendir 打开目录
  • readdir 获取子项
  • DT_DIRstat() 判断是否是目录
  • 必须忽略 ...

如果你是想用 C++ / Python / Shell 或需要过滤特定目录,可以继续问我。

0