linux

Linux readdir如何获取文件类型

小樊
44
2025-09-19 22:20:18
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的条目。要获取文件类型,您可以使用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");
        exit(EXIT_FAILURE);
    }

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

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

        // 检查文件类型
        switch (file_stat.st_mode & S_IFMT) {
            case S_IFREG:
                printf("%s: 普通文件\n", entry->d_name);
                break;
            case S_IFDIR:
                printf("%s: 目录\n", entry->d_name);
                break;
            case S_IFCHR:
                printf("%s: 字符设备\n", entry->d_name);
                break;
            case S_IFBLK:
                printf("%s: 块设备\n", entry->d_name);
                break;
            case S_IFIFO:
                printf("%s: 管道\n", entry->d_name);
                break;
            case S_IFSOCK:
                printf("%s: 套接字\n", entry->d_name);
                break;
            default:
                printf("%s: 未知类型\n", entry->d_name);
                break;
        }
    }

    closedir(dir);
    return 0;
}

这个示例程序首先打开当前目录,然后使用readdir函数读取目录中的每个条目。对于每个条目,它使用stat函数获取文件的详细信息,然后检查st_mode字段以确定文件类型。最后,它输出每个文件的类型。

0
看了该问题的人还看了