Readdir returns dirent with d_type == DT_UNKNOWN for directories. and

I have the following code that mimics 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;
}

For some reason, when I run the program, it says that d_typerelated to .and ..is unknown:

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~

From my research, it turns out that it 0is equal DT_UNKNOWNin accordance with this answer . Why is this happening (instead of yielding DT_DIR)?

+4
source share
1 answer

The manpage for readdir()clearly states that the file system can return DT_UNKNOWNto struct dirent:

( : Btrfs, ext2, ext3 ext4) d_type. DT_UNKNOWN.

, . , , readdir().

, d_type , , (l)stat().

+5

Source: https://habr.com/ru/post/1688608/


All Articles