admin管理员组

文章数量:1125093

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.

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.

Share Improve this question edited 2 days ago Jabberwocky 50.7k18 gold badges68 silver badges124 bronze badges asked 2 days ago Tempest_SwordTempest_Sword 231 silver badge6 bronze badges 6
  • 4 The only fields in the dirent structure that are mandated by POSIX.1 are d_name and d_ino. Do you have some specific operating system and/or standard in mind? – teapot418 Commented 2 days ago
  • If your target platform supports it, then use it. If it doesn't, then don't use it. In the latter case there are no specific file types. For exemple on Windows AFAIK there are only regular files that can be in a struct dirent. – Jabberwocky Commented 2 days ago
  • I Ubuntu POSIX compliant? – Tempest_Sword Commented 2 days ago
  • 1 @Tempest_Sword that fact that a system is posix compliant is irrelevant here because the only fields in the dirent structure that are mandated by POSIX.1 are d_name and d_ino. IOW if your system is posix compliant, there is no guarantee that d_type is supported. – Jabberwocky Commented 2 days ago
  • ... but also no reason to assume that d_type is not supported. POSIX specifies members that must be present in the structure. It does not limit the structure to only those members. – John Bollinger Commented 2 days ago
 |  Show 1 more comment

1 Answer 1

Reset to default 4

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.

本文标签: cAre all elements of the dirent structure open to useStack Overflow