readdir: determining if file is a dir

If I'm using opendir+readdir to traverse the filesystem -- how can I tell whether or not the files provided by readdir are directories and not additional files?

I'm using this page for reference:

http://linux.die.net/man/3/readdir

I see there's a "d_type" member there, but that page seems to give no indication of possible values and their significance.

Any help appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
/*
 * File types
 */
#define DT_UNKNOWN       0
#define DT_FIFO          1
#define DT_CHR           2
#define DT_DIR           4
#define DT_BLK           6
#define DT_REG           8
#define DT_LNK          10
#define DT_SOCK         12
#define DT_WHT          14 


http://www.gsp.com/cgi-bin/man.cgi?section=5&topic=dir
excellent -- thanks
The man page does explicitly say that the use of fields other than d_name harms portability -- and I'll add that it does even among unices.

To determine whether or not a given file is a directory, use stat(2) and the S_ISDIR macro.
http://linux.die.net/man/2/stat

1
2
3
4
5
6
7
8
9
10
DIR* dir = ...
  ...
  struct dirent* direntry = readdir( dir );
  struct stat entrystat;
  if (stat( direntry->d_name, &entrystat )) fooey();
  if (S_ISDIR( entrystat.st_mode ))
    {
    // entry is a directory
    }
  ...

Hope this helps.
Last edited on
Topic archived. No new replies allowed.