温馨提示×

readdir如何实现Linux目录的递归遍历

小樊
40
2025-11-01 09:33:51
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的条目。要实现目录的递归遍历,你需要结合其他函数,如opendirclosedirstat。以下是一个使用C语言实现的递归遍历目录的示例:

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

void list_directory_contents(const char *path);

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <directory_path>\n", argv[0]);
        return 1;
    }

    list_directory_contents(argv[1]);
    return 0;
}

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

    if (!dir) {
        perror("opendir");
        return;
    }

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

        snprintf(path_stat.path, sizeof(path_stat.path), "%s/%s", path, entry->d_name);
        if (stat(path_stat.path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(path_stat.st_mode)) {
            printf("Directory: %s\n", path_stat.path);
            list_directory_contents(path_stat.path);
        } else {
            printf("File: %s\n", path_stat.path);
        }
    }

    closedir(dir);
}

这个程序接受一个命令行参数,即要遍历的目录路径。list_directory_contents函数会打开目录,读取其中的条目,并检查每个条目是文件还是子目录。如果是子目录,它会递归地调用自身以继续遍历子目录。如果是文件,它会打印文件的路径。

要编译并运行此程序,请将其保存为recursive_directory_traversal.c,然后使用以下命令:

gcc -o recursive_directory_traversal recursive_directory_traversal.c
./recursive_directory_traversal /path/to/directory

/path/to/directory替换为要遍历的目录路径。

0