clsdirent.h

Are all elements of the dirent structure open to use?


I am currently working on the implementation of my own "ls" command. I've been relying on the structure but I found an old post stating that some members of this structure such as d_type shouldn't be used.

I have already been able to list the files in the repository but I want to sort the files depending of their type hence the reason of my post.

So I am just wondering if there is a way other than using the d_type or if it is not actually wrong to use it.


Solution

  • If your question is about Ubuntu, that is Linux/glibc, described in detail by the readdir man page. Its dirent does have the d_type field. But keep in mind that it may give you DT_UNKNOWN at any time and you should be able to deal with it.

    The most portable (POSIX) way to code this would be not to rely on d_type at all as POSIX only mandates the d_name and d_ino fields.

    So what to do if you either don't have the d_type field or it has given you an unknown value? Use one of the stat functions (for listing files probably lstat to not follow links) and then for glibc you can follow Testing the Type of a File on the st_mode field in the result of stat.