linux

Linux中copendir的递归遍历方法

小樊
43
2025-09-19 17:49:48
栏目: 智能运维

在Linux中,使用copendir函数可以打开一个目录流,但是它本身并不提供递归遍历的功能。要实现递归遍历目录,你需要结合readdir函数以及递归算法。下面是一个简单的示例代码,展示了如何使用copendirreaddir函数递归遍历目录:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.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) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        // 忽略当前目录和上级目录的特殊条目
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 构建完整的文件或目录路径
        char full_path[PATH_MAX];
        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(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return EXIT_FAILURE;
    }

    list_directory_contents(argv[1]);

    return EXIT_SUCCESS;
}

这个程序接受一个目录路径作为命令行参数,并递归地列出该目录下的所有文件和子目录。它首先打开目录,然后读取目录中的每个条目。对于每个条目,它构建完整的路径,并使用stat函数获取文件或目录的信息。如果条目是一个目录,程序递归调用list_directory_contents函数;如果是一个文件,它打印出文件的完整路径。

要编译这个程序,你可以使用gcc命令:

gcc -o listdir listdir.c

然后运行程序,传入你想要遍历的目录路径:

./listdir /path/to/directory

请注意,这个程序没有处理符号链接,如果目录中包含符号链接到子目录的情况,它可能会导致无限递归。处理符号链接需要额外的逻辑来检查链接目标是否已经在当前递归路径中。

0
看了该问题的人还看了