How can I find the size of all files located inside a folder?

后端 未结 12 2401
萌比男神i
萌比男神i 2020-12-06 05:49

Is there any API in c++ for getting the size of a specified folder?

If not, how can I get the total size of a folder including all subfolders and files?

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 06:03

    Actually I don't want to use any third party library. Just want to implement in pure c++.

    If you use MSVC++ you have "as standard C++". But using boost or MSVC - both are "pure C++".

    If you don’t want to use boost, and only the C++ std:: library this answer is somewhat close. As you can see here, there is a Filesystem Library Proposal (Revision 4). Here you can read:

    The Boost version of the library has been in widespread use for ten years. The Dinkumware version of the library, based on N1975 (equivalent to version 2 of the Boost library), ships with Microsoft Visual C++ 2012.

    To illustrate the use, I adapted the answer of @Nayana Adassuriya , with very minor modifications (OK, he forgot to initialize one variable, and I use unsigned long long, and most important was to use: path filePath(complete (dirIte->path(), folderPath)); to restore the complete path before the call to other functions). I have tested and it work well in windows 7.

    #include 
    #include 
    #include 
    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; }
             }
          }
        }
    
    int main()
    {
        unsigned long long  f_size=0;
        getFoldersize("C:\\Silvio",f_size);
        cout << f_size << endl;
        system("pause");
        return 0;
    }
    

提交回复
热议问题