linux

readdir如何获取文件类型

小樊
39
2025-07-26 15:00:18
栏目: 编程语言

readdir 函数本身并不直接提供文件类型信息,它只是读取目录中的条目。要获取文件类型,你可以使用 stat 函数来获取文件的详细信息,然后根据返回的 st_mode 字段来判断文件类型。

以下是一个使用 readdirstat 函数获取文件类型的示例:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.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) {
        // 获取文件的完整路径
        char file_path[PATH_MAX];
        snprintf(file_path, sizeof(file_path), "./%s", entry->d_name);

        // 获取文件的详细信息
        if (stat(file_path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 根据 st_mode 判断文件类型
        if (S_ISREG(file_stat.st_mode)) {
            printf("%s is a regular file\n", entry->d_name);
        } else if (S_ISDIR(file_stat.st_mode)) {
            printf("%s is a directory\n", entry->d_name);
        } else if (S_ISCHR(file_stat.st_mode)) {
            printf("%s is a character device\n", entry->d_name);
        } else if (S_ISBLK(file_stat.st_mode)) {
            printf("%s is a block device\n", entry->d_name);
        } else if (S_ISFIFO(file_stat.st_mode)) {
            printf("%s is a FIFO (named pipe)\n", entry->d_name);
        } else if (S_ISSOCK(file_stat.st_mode)) {
            printf("%s is a socket\n", entry->d_name);
        } else {
            printf("%s is of unknown type\n", entry->d_name);
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个示例程序会读取当前目录下的所有文件和子目录,并使用 stat 函数获取它们的详细信息。然后根据 st_mode 字段判断文件类型,并输出相应的信息。

0
看了该问题的人还看了