linux

readdir如何与其他文件操作函数配合使用

小樊
48
2025-06-12 03:53:10
栏目: 编程语言

readdir 是一个用于读取目录内容的函数,通常与 opendirclosedir 和其他文件操作函数一起使用。以下是一个简单的示例,展示了如何使用这些函数来遍历一个目录及其子目录中的所有文件和文件夹:

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

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) {
        // 跳过当前目录(.)和上级目录(..)
        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);

        // 获取文件/目录信息
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        // 输出文件/目录名
        printf("%s\n", full_path);

        // 如果是目录,则递归遍历
        if (S_ISDIR(path_stat.st_mode)) {
            list_directory_contents(full_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;
}

这个示例程序接受一个目录作为命令行参数,然后使用 opendir 打开该目录。接着,它使用 readdir 函数读取目录中的每个条目。对于每个条目,它使用 stat 函数获取文件或目录的信息,然后输出文件或目录的完整路径。如果遇到子目录,程序会递归地调用 list_directory_contents 函数来遍历子目录。

注意:这个示例程序没有处理符号链接和其他特殊文件类型。在实际应用中,你可能需要根据需求对这些情况进行额外的处理。

0
看了该问题的人还看了