1

readdir returns info about all item within the directory. How can I tell if the item is file or directory?

Thank you.

EDIT. Sorry, forgot to mention, that my time target platform is iOS and android.

2
  • I'm not sure that readdir is usable within an iOS application. In any case, on that platform you'll be better served by using NSFileManager and the -fileType helper method, which can identify directories. Commented Nov 11, 2011 at 15:54
  • After looking into it, it appears readdir is usable on iOS, but there are some bugs with its implementation on iOS 4.x: devforums.apple.com/message/251591 . I'd still recommend using the higher-level abstraction of NSFileManager for this. Commented Nov 11, 2011 at 15:57

4 Answers 4

6

Check for d_type being D_DIR.

Sign up to request clarification or add additional context in comments.

3 Comments

@pic11, see my comment to Basile's answer.
Using d_type is likely to be about 50-1000 times faster than calling stat for every entry, but you should probably include fallback code for systems where d_type does not exist or in case it's not filled in.
@R.., yes, that's a good idea. But it all depends on OP's intentions. It might also be that the OP wants to examine the link target, I have no idea ;-)
1

dirent contains a member d_type which can evaluate to 0x8 if it is a file, so:

struct dirent *DirEntry; ... if ( DirEntry->d_type == 0x8) //is a file 

Comments

1

It depends, on the standard "POSIX" readdir operation you do not have the field d_type

According to POSIX, the dirent structure contains a field char d_name[] of unspecified size, > with at most NAME_MAX characters preceding the terminating null byte. POSIX.1-2001 also documents the field ino_t d_ino as an XSI extension. Use of other > fields will harm the portability of your programs.

The "standard way" is to do a lstat call on you file/dir and check the st_mode field of the struct stat, if your st_mode match S_ISDIR, you have a dir.

Comments

0

You can also compute a path for each entry in the directory (but perhaps you can skip . & .. entries) and use the stat system call on that path.

This is useful if you want more information (e.g. modification time, size, ...) on the path.

2 Comments

It might also be useful in case of the system that doesn't support d_type, though since the question is tagged linux, it is very unlikely to be a problem.
There's no need to compute the path. (At least, not on Linux > 2.6.16) Since readdir is being used, there is already an open dirent so you can use fstatat with the relative path given in d_name. (Use dirfd() to get the fd).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.