温馨提示×

Ubuntu中如何通过copendir访问子目录

小樊
43
2025-11-07 15:01:17
栏目: 智能运维

在Ubuntu中,opendir()函数用于打开一个目录流,以便读取目录中的文件和子目录。要使用opendir()访问子目录,你需要结合其他函数,如readdir()closedir()。以下是一个简单的示例,展示了如何使用这些函数访问子目录:

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

int main() {
    DIR *dir;
    struct dirent *entry;
    char path[1024];

    // 打开当前目录
    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        exit(EXIT_FAILURE);
    }

    // 读取目录中的条目
    while ((entry = readdir(dir)) != NULL) {
        // 跳过当前目录(".")和上级目录("..")
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 构建子目录的完整路径
        snprintf(path, sizeof(path), "./%s", entry->d_name);

        // 检查是否为目录
        if (entry->d_type == DT_DIR) {
            printf("子目录: %s\n", path);

            // 递归访问子目录
            access_subdirectory(path);
        }
    }

    // 关闭目录流
    closedir(dir);
    return 0;
}

void access_subdirectory(const char *path) {
    DIR *dir;
    struct dirent *entry;
    char sub_path[1024];

    // 打开子目录
    dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    // 读取子目录中的条目
    while ((entry = readdir(dir)) != NULL) {
        // 跳过当前目录(".")和上级目录("..")
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 构建子子目录的完整路径
        snprintf(sub_path, sizeof(sub_path), "%s/%s", path, entry->d_name);

        // 检查是否为目录
        if (entry->d_type == DT_DIR) {
            printf("  子子目录: %s\n", sub_path);

            // 递归访问子子目录
            access_subdirectory(sub_path);
        }
    }

    // 关闭目录流
    closedir(dir);
}

这个示例程序首先打开当前目录(“.”),然后读取其中的条目。对于每个条目,如果它是一个目录,程序会打印出它的名称,并递归地访问该子目录。access_subdirectory()函数执行类似的操作,但针对给定的子目录路径。

0