温馨提示×

readdir如何处理文件类型

小樊
46
2025-08-02 07:17:23
栏目: 编程语言

readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。它会返回目录中的下一个条目(文件或子目录)。要处理不同类型的文件,你需要检查每个条目的类型。这可以通过使用 stat 函数来实现。

以下是一个简单的示例,展示了如何使用 readdirstat 函数来处理目录中的不同文件类型:

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

int main() {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;

    dir = opendir("."); // 打开当前目录
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    while ((entry = readdir(dir)) != NULL) {
        // 跳过当前目录和上级目录的特殊条目
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 使用 stat 函数获取文件信息
        if (stat(entry->d_name, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 检查文件类型
        if (S_ISREG(file_stat.st_mode)) {
            printf("Regular file: %s\n", entry->d_name);
        } else if (S_ISDIR(file_stat.st_mode)) {
            printf("Directory: %s\n", entry->d_name);
        } else if (S_ISCHR(file_stat.st_mode)) {
            printf("Character device: %s\n", entry->d_name);
        } else if (S_ISBLK(file_stat.st_mode)) {
            printf("Block device: %s\n", entry->d_name);
        } else if (S_ISFIFO(file_stat.st_mode)) {
            printf("FIFO (pipe): %s\n", entry->d_name);
        } else if (S_ISSOCK(file_stat.st_mode)) {
            printf("Socket: %s\n", entry->d_name);
        } else {
            printf("Unknown file type: %s\n", entry->d_name);
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个示例程序会打开当前目录,然后使用 readdir 函数读取目录中的每个条目。对于每个条目,它使用 stat 函数获取文件信息,然后检查文件类型。根据文件类型,它会打印相应的消息。

0