readdir如何实现递归遍历

readdir如何实现递归遍历

readdir 函数本身并不提供递归遍历目录的功能,它只是用于读取指定目录下的文件和子目录。要实现递归遍历,你需要结合 readdir 和其他函数(如 opendir、closedir 和 stat)来完成。以下是一个使用 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;    <span>struct dirent *entry;</span>    <span>struct stat path_stat;</span>    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 (stat(path_stat.path, &path_stat) == -1) {            perror("stat");            continue;        }        if (S_ISDIR(path_stat.st_mode)) {            printf("Directory: %sn", path_stat.path);            list_directory_contents(path_stat.path);        } else {            printf("File: %sn", path_stat.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;}

登录后复制

文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/716929.html

(0)
上一篇 2025-06-09 13:05
下一篇 2025-06-09 13:05

相关推荐