位置:首页 > Shell > copendir在递归遍历目录中的应用与实现

copendir在递归遍历目录中的应用与实现

时间:2026-08-21  |  作者:游戏探长  |  阅读:0

copendir 函数的作用

copendir 这个函数,说白了就是用来打开一个目录的。

它返回一个指向 DIR 结构的指针,里面装着目录流的信息。

在递归遍历目录这种场景里,它通常和 readdirclosedir 搭伙干活。基本流程是:先打开目录,再逐个读取条目,最后判断条目是不是子目录。

如果是子目录,就递归调用遍历函数,继续往下挖。

递归遍历目录示例

下面这段代码,就是一个典型的递归遍历目录的例子:

#include 
#include 
#include 
#include 
#include 

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

    dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        // Skip current and parent directory entries
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // Construct the full path of the entry
        char full_path[PATH_MAX];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        // Get the file status
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        // If it's a directory, recurse
        if (S_ISDIR(path_stat.st_mode)) {
            printf("Directory: %sn", full_path);
            list_directory_contents(full_path);
        } else {
            // Otherwise, print the file name
            printf("File: %sn", full_path);
        }
    }

    closedir(dir);
}

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

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

代码逻辑说明

在这个例子中,list_directory_contents 函数接收一个目录路径作为参数。

  • 先打开目录:通过 opendir 获取目录流。
  • 循环读取条目:使用 readdir 逐个获取目录中的内容。
  • 判断条目类型:调用 stat 获取文件状态,判断是文件还是目录。
  • 递归处理子目录:如果是目录,就打印目录名,并递归调用自身。
  • 输出普通文件:如果是文件,就直接打印文件名。

这里有一个关键点:跳过了当前目录(.)和父目录(..)这两个特殊条目。

如果不跳过它们,递归会陷入死循环。

如何使用

用起来也很简单:把代码编译成可执行文件,然后在命令行里指定要遍历的目录路径就行。

比如:

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

这样,程序就会递归地列出指定目录下所有文件和子目录,一层层展示出来。

免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。

相关文章

更多

精选合集

更多

大家都在玩

热门话题

大家都在看

更多