温馨提示×

Linux readdir如何支持多种文件类型

小樊
77
2025-11-19 17:39:39
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的条目。默认情况下,readdir会返回目录中的所有文件和子目录,不论它们的类型。如果你想要对不同类型的文件执行不同的操作,你需要在读取到每个条目后,使用其他函数来检查它的类型。

以下是一个简单的示例,展示了如何使用readdir以及stat函数来区分目录中的文件类型:

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.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);

        // 获取文件的stat信息
        if (stat(path, &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 (named pipe): %s\n", entry->d_name);
        } else if (S_ISSOCK(file_stat.st_mode)) {
            printf("Socket: %s\n", entry->d_name);
        } else {
            printf("Other type: %s\n", entry->d_name);
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个程序接受一个目录路径作为命令行参数,然后使用opendir打开该目录,使用readdir读取目录中的每个条目。对于每个条目,它使用stat函数获取文件的详细信息,并根据st_mode字段检查文件类型。

注意,这个程序只是一个简单的示例,实际使用时可能需要处理更多的错误情况和边缘情况。

0