温馨提示×

Linux readdir的文件类型判断

小樊
44
2025-11-21 16:57:58
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的文件和子目录。当你使用readdir读取目录时,它会返回一个指向dirent结构体的指针,其中包含了文件或目录的信息。要判断文件类型,你可以检查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:表示套接字文件
  8. DT_UNKNOWN:表示未知类型

以下是一个简单的示例,展示了如何使用readdird_type字段来判断文件类型:

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

int main() {
    DIR *dir;
    struct dirent *entry;

    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);

        struct stat path_stat;
        char full_path[PATH_MAX];

        snprintf(full_path, sizeof(full_path), "./%s", entry->d_name);
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        switch (entry->d_type) {
            case DT_REG:
                printf("  Type: Regular file\n");
                break;
            case DT_DIR:
                printf("  Type: Directory\n");
                break;
            case DT_LNK:
                printf("  Type: Symbolic link\n");
                break;
            case DT_BLK:
                printf("  Type: Block device\n");
                break;
            case DT_CHR:
                printf("  Type: Character device\n");
                break;
            case DT_FIFO:
                printf("  Type: Named pipe (FIFO)\n");
                break;
            case DT_SOCK:
                printf("  Type: Socket\n");
                break;
            case DT_UNKNOWN:
                printf("  Type: Unknown\n");
                break;
            default:
                printf("  Type: Unhandled\n");
                break;
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个示例程序会读取当前目录下的所有文件和子目录,并打印它们的名称和类型。注意,我们使用了stat函数来获取文件的详细信息,以便更准确地判断文件类型。

0