linux

Linux readdir如何实现递归遍历

小樊
36
2025-05-14 18:49:22
栏目: 智能运维

在Linux中,使用readdir函数可以实现对目录的递归遍历。以下是一个简单的示例,展示了如何使用readdiropendir等函数来递归遍历目录及其子目录:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.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 (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>\n", argv[0]);
        return EXIT_FAILURE;
    }

    list_directory_contents(argv[1]);

    return EXIT_SUCCESS;
}

代码解释

  1. 包含头文件

    • stdio.h:用于标准输入输出。
    • stdlib.h:用于标准库函数。
    • dirent.h:用于目录操作。
    • string.h:用于字符串操作。
    • sys/stat.h:用于文件状态信息。
  2. list_directory_contents函数

    • 接受一个目录路径作为参数。
    • 使用opendir打开目录。
    • 使用readdir读取目录中的条目。
    • 对于每个条目,使用stat获取文件状态信息。
    • 如果条目是目录,则递归调用list_directory_contents
    • 如果条目是文件,则打印文件路径。
    • 关闭目录。
  3. main函数

    • 检查命令行参数,确保提供了一个目录路径。
    • 调用list_directory_contents函数开始递归遍历。

编译和运行

使用以下命令编译程序:

gcc -o listdir listdir.c

然后运行程序并指定要遍历的目录:

./listdir /path/to/directory

这个程序会递归地遍历指定目录及其所有子目录,并打印出每个文件和目录的路径。

0
看了该问题的人还看了