linux

copendir在Linux中如何实现目录遍历

小樊
35
2025-06-26 03:09:10
栏目: 智能运维

copendir() 是一个在 Linux 系统中用于打开目录的函数,它是 dirent.h 头文件的一部分。要实现目录遍历,你需要结合使用 opendir()readdir()closedir() 函数。下面是一个简单的示例,展示了如何使用这些函数遍历目录:

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

int main() {
    DIR *dir;
    struct dirent *entry;

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

    // 遍历目录
    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    // 关闭目录
    closedir(dir);

    return EXIT_SUCCESS;
}

这个示例程序会打开当前目录(.),然后使用 readdir() 函数读取目录中的每个条目。对于每个条目,它将打印出条目的名称。最后,它使用 closedir() 函数关闭目录。

如果你想要递归地遍历目录及其子目录,你可以编写一个递归函数来实现这个功能。下面是一个简单的递归目录遍历示例:

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

void list_directory_contents(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat path_stat;

    // 打开目录
    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;
        }

        // 拼接完整路径
        char full_path[1024];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        // 获取文件/目录信息
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        // 如果是目录,则递归遍历
        if (S_ISDIR(path_stat.st_mode)) {
            list_directory_contents(full_path);
        } else {
            printf("%s\n", full_path);
        }
    }

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

int main() {
    list_directory_contents(".");
    return EXIT_SUCCESS;
}

这个示例程序定义了一个名为 list_directory_contents 的递归函数,它会遍历指定路径下的所有文件和目录。对于每个目录,它会递归地调用自身。

0
看了该问题的人还看了