2

i'd like to check when I go over all files on directory, if one of the files/items on the directory is folder (another directory)

code I have started from (using dirent.h):

DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
  /* print all the files and directories within directory */
  while ((ent = readdir (dir)) != NULL) {
    if (ent.is_folder()) // here is what I want to implement
      printf ("Folder: %s\n", ent->d_name);
    else
      printf("File %s\n", ent->d_name);
  }
  closedir (dir);
} else {
  /* could not open directory */
  perror ("");
  return EXIT_FAILURE;
}
Raz Omry
  • 255
  • 1
  • 6
  • 18
  • what's the problem that you got? – P.A May 24 '17 at 16:59
  • there is no function ent.is_folder() you know.. it's c. If you see I want to check if ent (which is read from the dir) is an directory (folder) or a file – Raz Omry May 24 '17 at 17:00
  • take a look at https://stackoverflow.com/questions/4553012/checking-if-a-file-is-a-directory-or-just-a-file – P.A May 24 '17 at 17:04
  • https://stackoverflow.com/questions/1036625/differentiate-between-a-unix-directory-and-file-in-c-and-c – P.A May 24 '17 at 17:11
  • I'm confused. You're calling `opendir` and `readdir` to get a `dirent` (not `openfolder` and `readfolder` to get a `folderent`) and you want to know if the `dirent` is a "directory", so why is the word "folder" even used in the question, and why do you want to implement `is_folder()` instead of `is_directory()`? – William Pursell May 24 '17 at 22:30

1 Answers1

6

Readdir() returns a structure, in which you have a variable to check if your directory contains files and/or directories. Here is the structure :

struct dirent {
    ino_t          d_ino;       /* numéro d'inœud */
    off_t          d_off;       /* décalage jusqu'à la dirent suivante 
*/
    unsigned short d_reclen;    /* longueur de cet enregistrement */
    unsigned char  d_type;      /* type du fichier */
    char           d_name[256]; /* nom du fichier */
};

So you will use in your code : ent->d_type to access this variable. Then with the flag DT_DIR you will check if it's a directory, and if it is a file with the flag DT_REG.

The code below works :

DIR *dir;
struct dirent *ent;

if ((dir = opendir ("c:\\src\\")) != NULL)
{
    /* print all the files and directories within directory */
    while ((ent = readdir (dir)) != NULL) {
        if (ent->d_type == DT_DIR)// here is what I want to implement
            printf ("Folder: %s\n", ent->d_name);
        else if (ent->d_type == DT_REG)
            printf("File %s\n", ent->d_name);
    }
    closedir (dir);
}
else
{
/* could not open directory */
    perror ("");
        return EXIT_FAILURE;
}
MIG-23
  • 511
  • 3
  • 11