温馨提示×

Linux readdir如何实现文件类型区分

小樊
35
2025-12-01 13:18:11
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的条目。要区分文件类型,你可以使用stat结构体和S_ISREGS_ISDIR等宏来检查每个条目的类型。以下是一个简单的示例,展示了如何使用readdirstat来区分文件类型:

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

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>
", argv[0]);
        return EXIT_FAILURE;
    }

    dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    while ((entry = readdir(dir)) != NULL) {
        // 获取文件的完整路径
        char path[PATH_MAX];
        snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);

        // 使用stat获取文件信息
        if (stat(path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

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

    closedir(dir);
    return EXIT_SUCCESS;
}

这个程序接受一个目录作为命令行参数,然后使用readdir读取目录中的每个条目。对于每个条目,它使用stat函数获取文件的状态信息,并根据st_mode字段使用宏(如S_ISREGS_ISDIR等)来检查文件类型。然后,它打印出每个条目的类型。

0