我有以下模仿 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 answer,0
似乎等于 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/