温馨提示×

ubuntu readdir 文件类型

小樊
42
2025-12-06 02:46:18
栏目: 智能运维

在Ubuntu中,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:未知类型

你可以使用d_type成员变量来判断readdir函数返回的文件类型。例如:

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

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

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

    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
        if (entry->d_type == DT_REG) {
            printf("  Type: Regular file\n");
        } else if (entry->d_type == DT_DIR) {
            printf("  Type: Directory\n");
        } else if (entry->d_type == DT_LNK) {
            printf("  Type: Symbolic link\n");
        }
        // ... 其他类型
    }

    closedir(dir);
    return 0;
}

这个示例程序会列出当前目录下的所有文件和子目录,并打印它们的类型。

0