温馨提示×

CentOS readdir文件类型判断

小樊
38
2025-03-03 15:40:15
栏目: 智能运维
Centos服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在 CentOS 系统中,你可以使用 readdir 函数来读取目录中的文件和子目录。为了判断文件类型,你可以检查 readdir 返回的 dirent 结构体中的 d_type 字段。以下是一个简单的示例,展示了如何使用 readdir 函数和 d_type 字段来判断文件类型:

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

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

    if (argc != 2) {
        printf("Usage: %s <directory>\n", argv[0]);
        return 1;
    }

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

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

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

        // 判断文件类型
        switch (file_stat.st_mode & S_IFMT) {
            case S_IFREG:
                printf("%s is a regular file\n", entry->d_name);
                break;
            case S_IFDIR:
                printf("%s is a directory\n", entry->d_name);
                break;
            case S_IFCHR:
                printf("%s is a character device\n", entry->d_name);
                break;
            case S_IFBLK:
                printf("%s is a block device\n", entry->d_name);
                break;
            case S_IFIFO:
                printf("%s is a FIFO (named pipe)\n", entry->d_name);
                break;
            case S_IFSOCK:
                printf("%s is a socket\n", entry->d_name);
                break;
            default:
                printf("%s is of unknown type\n", entry->d_name);
                break;
        }
    }

    closedir(dir);
    return 0;
}

这个程序接受一个目录作为命令行参数,然后使用 readdir 函数读取目录中的所有条目。对于每个条目,它使用 stat 函数获取文件的状态信息,并根据 st_mode 字段判断文件类型。最后,它将文件类型打印到控制台。

要编译此程序,请将其保存为 file_type_checker.c,然后在终端中运行以下命令:

gcc -o file_type_checker file_type_checker.c

现在你可以使用这个程序来检查 CentOS 系统中的文件类型。例如:

./file_type_checker /path/to/directory

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:CentOS readdir支持哪些文件类型

0