Home > Net >  How do I use recursion to find all the directories?
How do I use recursion to find all the directories?

Time:12-27

I need to write code that can find the largest folder on the entire system. Including system directories such as sys.

How to find the largest folder in the system, including sys?

That is, I set the initial path to C:\\, and then the folder search should begin

The code I used to determine the size of the folder

#include <iostream>
#include <string>
#include <filesystem>
using namespace std;
using namespace std::tr2::sys;

void  getFoldersize(string rootFolder,unsigned long long & f_size)
{
   path folderPath(rootFolder);                      
   if (exists(folderPath))
   {
        directory_iterator end_itr;
        for (directory_iterator dirIte(rootFolder); dirIte != end_itr;   dirIte )
        {
            path filePath(complete (dirIte->path(), folderPath));
           try{
                  if (!is_directory(dirIte->status()) )
                  {
                      f_size = f_size   file_size(filePath);                      
                  }else
                  {
                      getFoldersize(filePath,f_size);
                  }
              }catch(exception& e){  cout << e.what() << endl; }
         }
      }
    }

CodePudding user response:

I have solved my question, here is a piece of code that helps to recursively go through all the folders in the root folder and find the size of each folder separately, someone might need it.

std::map<std::string, intmax_t> sizeFolder;

std::uintmax_t directorySize(const std::filesystem::path& directory)
{
    std::uintmax_t size{ 0 };
    for (const auto& entry : std::filesystem::recursive_directory_iterator(directory))
    {
        if (entry.is_regular_file() && !entry.is_symlink())
        {
            size  = entry.file_size();
        }
    }
    return size;
}

void ls_recursive(const std::filesystem::path& path)
{
    int_fast64_t count = 0;
    for(const auto& p: std::filesystem::recursive_directory_iterator(path,std::filesystem::directory_options::skip_permission_denied))
    {
        if (std::filesystem::is_directory(p)) 
        {
            uintmax_t temp = 0;
            temp = directorySize(p.path());
            sizeFolder[p.path().filename().string()] = temp;
        }
    }
}
  • Related