ubuntu

ubuntu readdir如何实现目录递归读取

小樊
51
2025-10-03 06:56:02
栏目: 智能运维

在Ubuntu中,你可以使用C语言的dirent.h库来实现目录递归读取。下面是一个简单的示例代码,展示了如何使用opendir()readdir()closedir()函数来递归地读取目录及其子目录中的所有文件和文件夹。

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

    if (!(dir = opendir(path))) {
        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);
}

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

    list_directory_contents(argv[1]);

    return EXIT_SUCCESS;
}

将上述代码保存为list_directory_contents.c,然后使用以下命令编译:

gcc -o list_directory_contents list_directory_contents.c

运行编译后的程序,传入要递归读取的目录路径作为参数:

./list_directory_contents /path/to/directory

程序将输出指定目录及其子目录中的所有文件和文件夹。

0
看了该问题的人还看了