2017-11-02 3 views
4

내가 ls을 mimicks 다음 코드가 : 어떤 이유디렉토리의 경우 d_type == DT_UNKNOWN 인 dirent를 반환하는 readdir입니다. 및

#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를 알 수 없음을 말하고있다 :

[email protected]:~/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~ 

조사 결과, 0this answer에 따르면 DT_UNKNOWN과 같습니다. 왜 이런 현상이 발생합니까 (DT_DIR을 산출하는 대신)?

+0

FWIW 당신은 ​​그 지식을 단순히 하드 코딩 할 수 있습니다. 및 .. 디렉토리입니다. 그것들은 POSIX에 의해 위임되었습니다. –

답변

5

readdir()의 맨 명확하게 파일 시스템이 struct direntDT_UNKNOWN를 반환하는 무료입니다, 상태 : 현재

일부 파일 시스템을 (그 (것)들의 사이에서 : BTRFS, EXT2, EXT3 나 ext4)를 완벽하게 지원을 d_type에 파일 유형을 반환하는 경우. 모든 응용 프로그램은 DT_UNKNOWN의 반환을 올바르게 처리해야합니다. 일부 파일 시스템과 파일 형식은 디렉토리 자체에 저장 하지 때문에

이 주로 성능상의 이유로 이루어집니다. 이 경우 큰 디렉토리의 경우 전체 블록 장치에 흩어져있는 많은 읽기가 readdir()을 상당히 느리게 만듭니다.

파일 시스템에 d_type이 실제로 필요하다면 제대로 채워지지 않으므로 (l)stat()을 명시 적으로 호출해야합니다.

+0

XFS는이 경우에 악의적 인 요인의 완벽한 예입니다. – Petesh

+0

[현재 XFS는'd_type'을 지원합니다.] (https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=0cb97766f2928579f1029ea7b28ae946cdd6fbe1) –

관련 문제