0
votes

I have a C program in Linux, which collects directory entries (of type 'struct dirent*') from a struct DIR and displays them. Now, my goal is to recursively traverse through the file system so I need to identify Directories and Files seperately.

DIR* cwd = opendir(".");
struct dirent* directoryEntry = NULL;
while((directoryEntry = readdir(cwd)) != NULL) {
    printf("%s ", directoryEntry->d_name);
}
closedir(cwd);

I know you could say that we can identify files if there is some extension ".mp4" or ".txt" at the end. But files without any extension may also exist.

Is there any attribute of struct dirent* which tells whether it is a file or a directory?

1
And if your filesystem doesn't support d_type, fall back on lstat()Shawn
ftw() might also be of interest.Shawn

1 Answers

1
votes

You may try this:

   struct dirent {
       ino_t          d_ino;       /* Inode number */
       off_t          d_off;       /* Not an offset; see below */
       unsigned short d_reclen;    /* Length of this record */
       unsigned char  d_type;      /* Type of file; not supported
                                      by all filesystem types */
       char           d_name[256]; /* Null-terminated filename */
   };

And once you have it, check if d_type contains DT_DIR:

  DT_BLK      This is a block device.
  DT_CHR      This is a character device.
  DT_DIR      This is a directory.           <<---- this one!!!
  DT_FIFO     This is a named pipe (FIFO).
  DT_LNK      This is a symbolic link.
  DT_REG      This is a regular file.
  DT_SOCK     This is a UNIX domain socket.
  DT_UNKNOWN  The file type could not be determined.

For the extra questions, please, refer to http://man7.org/linux/man-pages/man3/readdir.3.html