首页主机资讯readdir在Linux中如何实现递归遍历

readdir在Linux中如何实现递归遍历

时间2025-10-30 12:52:04发布访客分类主机资讯浏览1344
导读:在Linux中,可以使用readdir函数来实现递归遍历目录。以下是一个使用C语言编写的示例代码,展示了如何使用readdir函数递归遍历目录: #include <stdio.h> #include <stdlib.h&...

在Linux中,可以使用readdir函数来实现递归遍历目录。以下是一个使用C语言编写的示例代码,展示了如何使用readdir函数递归遍历目录:

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

        }
    

        snprintf(path_stat.path, sizeof(path_stat.path), "%s/%s", path, entry->
    d_name);
    
        if (lstat(path_stat.path, &
path_stat) == -1) {
    
            perror("lstat");
    
            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;

}
    

这个程序接受一个命令行参数,即要遍历的目录路径。它首先打开目录,然后使用readdir函数读取目录中的每个条目。对于每个条目,它检查是否为目录或文件,并相应地打印出来。如果条目是一个目录,程序会递归调用list_directory_contents函数来遍历该目录。

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

gcc -o recursive_directory_traversal recursive_directory_traversal.c

现在,您可以使用以下命令运行程序:

./recursive_directory_traversal /path/to/directory

这将递归遍历指定的目录并打印出所有文件和子目录。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: readdir在Linux中如何实现递归遍历
本文地址: https://pptw.com/jishu/738782.html
readdir在Linux中如何实现文件压缩与解压 Linux readdir如何筛选特定类型文件

游客 回复需填写必要信息