d3mage
d3mage

Reputation: 109

How to show only folders that have folders in it?

I need to output only that catalogues in current folder that, as I mentioned, have other folders in it.

#define _DEFAULT_SOURCE ;
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  char cwd[PATH_MAX];
  if (getcwd(cwd, sizeof(cwd)) != NULL)
   {
     struct dirent *pDirent; 
     DIR *pDir;
     pDir = opendir(cwd); 
     if(pDir != NULL)
     {
       struct stat sb; 
       struct dirent **folderArray; 
       folderArray = malloc(sizeof(struct stat)); 
       int foIndex = 0; 
      while ((pDirent = readdir(pDir)) != NULL) 
      {
        if(strcmp(pDirent->d_name, ".") != 0 
        && strcmp(pDirent->d_name, "..") != 0)
        {          
          stat(pDirent->d_name,&sb); 
          if((sb.st_mode & S_IFMT) == S_IFDIR)
          {      
           folderArray[foIndex++] = pDirent; 
           folderArray = realloc(folderArray, sizeof(struct stat)*(foIndex+1)); 
          }
        }     
      }   
  struct dirent *tDirent; 
  DIR *tDir;
  for(int i = 0; i<foIndex; ++i)
      { 
        tDir = opendir(folderArray[i]->d_name); 
        while ((tDirent = readdir(tDir)) != NULL) 
        {
          stat(tDirent->d_name,&sb); 
          if((sb.st_mode & S_IFMT) == S_IFDIR)
          {      
           printf("%s\n", folderArray[i]->d_name);
           break; 
          }
         closedir(tDir);
        }                
       }       
     closedir(pDir);
     free(pDirent);
     free(folderArray);
     }
   }
  return 0; 
}

I came up with this solution and now I'm wondering was it necessary to do create a new array or is it possible to do just in one loop? Because I can't figure out if I store in this array only dead-end pointers or I may use it to open my folders.

Upvotes: 0

Views: 135

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12732

You can avoid the extra array, but you will need to club sub directory loop.

  while ((pDirent = readdir(pDir)) != NULL) 
  {
    if(strcmp(pDirent->d_name, ".") != 0 
    && strcmp(pDirent->d_name, "..") != 0)
    {          
      stat(pDirent->d_name,&sb); 
      if((sb.st_mode & S_IFMT) == S_IFDIR)
      {   

       /* Loop the sub directory */
       DIR *tDir = opendir(pDirent->d_name); 
       struct dirent *tDirent; 
       while ((tDirent = readdir(tDir)) != NULL) 
       {
         struct stat sb; 
         stat(tDirent->d_name,&sb); 
         if((sb.st_mode & S_IFMT) == S_IFDIR)
         {      
           printf("%s\n", tDirent->d_name);
           break; 
         }
       }  
       closedir(tDir);
      }
    }     
  }   

Upvotes: 1

Related Questions