c - readdir 为目录返回 d_type == DT_UNKNOWN 的 dirent。和

标签 c linux operating-system posix readdir

我有以下模仿 ls 的代码:

#include <dirent.h>
#include <stdio.h>

char* dirent_type_to_str(unsigned char dirent_type) {
  switch (dirent_type) {
  case DT_DIR:
    return "Dir ";
  case DT_REG:
    return "File";
  }

  printf("DEBUG: Unknown type %x\n", dirent_type);
  return "Unk ";
}

int main(int argc, char** argv) {
  char* dir_path = argc > 1 ? argv[1] : ".";
  DIR* dir_stream = opendir(dir_path);

  struct dirent* dirent_ptr;
  while (dirent_ptr = readdir(dir_stream)) {
    printf("%s %s\n", dirent_type_to_str(dirent_ptr->d_type), dirent_ptr->d_name);
  }

  closedir(dir_stream);

  return 0;
}

出于某种原因,当我运行该程序时,提示与 ... 关联的 d_type 未知:

james.ko@cslab1-20:~/Desktop/systems-11-02$ ./main
DEBUG: Unknown type 0
Unk  .
DEBUG: Unknown type 0
Unk  ..
File .gitignore
File main.o
File Makefile~
File Makefile
File main.c
Dir  .git
File main
File main.c~

根据我的研究,根据 this answer0 似乎等于 DT_UNKNOWN .为什么会发生这种情况(而不是产生 DT_DIR)?

最佳答案

readdir() 的联机帮助页明确指出,文件系统可以在 struct dirent 中自由返回 DT_UNKNOWN:

Currently, only some filesystems (among them: Btrfs, ext2, ext3, and ext4) have full support for returning the file type in d_type. All applications must properly handle a return of DT_UNKNOWN.

这主要是出于性能原因,因为对于某些文件系统,文件类型存储在目录本身中。在这种情况下,对于大型目录,分散在整个 block 设备上的许多读取会显着降低 readdir() 的速度。

因此,如果您确实需要文件系统上的 d_type,但无法正确填充它,则您必须显式调用 (l)stat()

关于c - readdir 为目录返回 d_type == DT_UNKNOWN 的 dirent。和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47078417/

相关文章:

c - ":"运算符是否等同于赋值运算符 "= "?

C结构体指针问题

linux - 了解 Docker Macvlan 网络

linux - 从 x86 asm 访问 linux 中的命令行参数的问题

c - 循环 strcmp 时出错

c - 估算微 Controller 的计算预算 (Arduino)

linux - Shell脚本在特定时间杀死进程,输入进程名称和时间

operating-system - Java 中的用户程序如何进行系统调用/调用内核子程序?

windows - 如何将Win2K3改造为工作站开发操作系统?

linux - 通过 fork : unexplainable behaviour 创建进程和子进程