linux

Linux readdir文件类型判断方法

小樊
35
2025-06-20 05:10:08
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的条目。要判断文件类型,可以使用stat结构体中的st_mode字段。以下是一个简单的示例,展示了如何使用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 file_stat;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", 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);

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

        // 判断文件类型
        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;
}

这个程序接受一个目录作为命令行参数,然后使用readdir函数读取目录中的条目。对于每个条目,我们使用stat函数获取文件的状态信息,并根据st_mode字段判断文件类型。这里使用了S_ISREGS_ISDIRS_ISCHRS_ISBLKS_ISFIFOS_ISSOCK宏来判断文件类型。

0
看了该问题的人还看了