温馨提示×

CentOS readdir中的文件类型如何判断

小樊
35
2025-12-25 12:07:17
栏目: 智能运维

在 CentOS 系统中,使用 readdir 函数读取目录时,可以通过检查 dirent 结构体中的 d_type 字段来判断文件类型。d_type 字段表示文件的类型,它是一个枚举值,可以是以下几种类型之一:

  1. DT_REG:普通文件
  2. DT_DIR:目录
  3. DT_LNK:符号链接
  4. DT_BLK:块设备文件
  5. DT_CHR:字符设备文件
  6. DT_FIFO:命名管道(FIFO)
  7. DT_SOCK:套接字文件

以下是一个简单的示例,展示如何使用 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;

    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) {
        struct stat file_stat;
        char path[PATH_MAX];

        snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);

        if (stat(path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        switch (entry->d_type) {
            case DT_REG:
                printf("%s is a regular file\n", entry->d_name);
                break;
            case DT_DIR:
                printf("%s is a directory\n", entry->d_name);
                break;
            case DT_LNK:
                printf("%s is a symbolic link\n", entry->d_name);
                break;
            case DT_BLK:
                printf("%s is a block device\n", entry->d_name);
                break;
            case DT_CHR:
                printf("%s is a character device\n", entry->d_name);
                break;
            case DT_FIFO:
                printf("%s is a named pipe (FIFO)\n", entry->d_name);
                break;
            case DT_SOCK:
                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 EXIT_SUCCESS;
}

编译并运行此程序,传入一个目录作为参数,程序将输出该目录中每个文件的类型。

0