Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a dir. entry returned by readdir is a directory, link or file. dent->d_type isn't showing the type

I am making a program which is run in a Linux shell, and accepts an argument (a directory), and displays all the files in the directory, along with their type.

Output should be like this:

 << ./Program testDirectory

 Dir directory1
 lnk linkprogram.c
 reg file.txt

If no argument is made, it uses the current directory. Here is my code:

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>

int main(int argc, char *argv[])
{
  struct stat info;
  DIR *dirp;
  struct dirent* dent;

  //If no args
  if (argc == 1)
  {

    argv[1] = ".";
    dirp = opendir(argv[1]); // specify directory here: "." is the "current directory"
    do
    {
      dent = readdir(dirp);
      if (dent)
      {
        printf("%c ", dent->d_type);
        printf("%s \n", dent->d_name);

        /* if (!stat(dent->d_name, &info))
         {
         //printf("%u bytes\n", (unsigned int)info.st_size);

         }*/
      }
    } while (dent);
    closedir(dirp);

  }

  //If specified directory 
  if (argc > 1)
  {
    dirp = opendir(argv[1]); // specify directory here: "." is the "current directory"
    do
    {
      dent = readdir(dirp);
      if (dent)
      {
        printf("%c ", dent->d_type);
        printf("%s \n", dent->d_name);
        /*  if (!stat(dent->d_name, &info))
         {
         printf("%u bytes\n", (unsigned int)info.st_size);
         }*/
      }
    } while (dent);
    closedir(dirp);

  }
  return 0;
}

For some reason dent->d_type is not displaying the type of file. I'm not really sure what to do, any suggestions?

like image 871
Barney Chambers Avatar asked May 30 '14 15:05

Barney Chambers


1 Answers

I was able to use d_type on ubuntu:

    switch (readDir->d_type)
    {
    case DT_DIR:
        printf("Dir: %s\n", readDir->d_name);
        break;
    case DT_REG:
        printf("File: %s\n", readDir->d_name);
        break;
    default:
        printf("Other: %s\n", readDir->d_name);
    }

The list of entry types can be found in dirent.h, (this could be different for os other than ubuntu):

dirent.h

#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
like image 105
Gary Davies Avatar answered Oct 14 '22 09:10

Gary Davies