当前位置: 代码网 > 科技>操作系统>系统进程 > 如何用copendir实现目录递归遍历

如何用copendir实现目录递归遍历

2025年04月03日 系统进程 我要评论
opendir 函数用于打开一个目录流,而 readdir 函数用于读取目录中的条目。要实现目录的递归遍历,你需要结合这两个函数,并对子目录进行递归调用。以下是一个使用 opendir 和 readd

opendir 函数用于打开一个目录流,而 readdir 函数用于读取目录中的条目。要实现目录的递归遍历,你需要结合这两个函数,并对子目录进行递归调用。

以下是一个使用 opendir 和 readdir 实现目录递归遍历的示例代码(c语言):

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

void list_directory_contents(<span>const char *path)</span> {
    dir *dir = opendir(path);
    if (dir == null) {
        perror("opendir");
        return;
    }

    <span>struct dirent *entry;</span>
    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);

        <span>struct stat path_stat;</span>
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        if (s_isdir(path_stat.st_mode)) {
            printf("directory: %s\n", full_path);
            list_directory_contents(full_path);
        } else {
            printf("file: %s\n", full_path);
        }
    }

    closedir(dir);
}

int main(<span>int argc, char *argv[])</span> {
    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 函数会打开目录,读取其中的条目,并检查每个条目是文件还是子目录。如果是子目录,它会递归调用自身以继续遍历子目录的内容。

编译并运行这个程序,传入一个目录路径作为参数,它将打印出该目录及其所有子目录中的文件和目录。

以上就是如何用copendir实现目录递归遍历的详细内容,更多请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com