如何查找位于文件夹内的所有文件的大小? [英] How can I find the size of all files located inside a folder?

查看:130
本文介绍了如何查找位于文件夹内的所有文件的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c ++ 中有任何API a>获取指定文件夹的大小?

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?

推荐答案


其实我不想使用任何第三方库。只需要
在纯c ++中实现。

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

如果使用MSVC ++,则 < filesystem> 作为标准C ++。
但是使用boost或MSVC - 都是纯C ++。

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

如果你不想使用boost,而只有C ++ std :: library,这个答案有点接近。您可以在此处看到 这里有一个文件系统库提案修订4) 。在这里您可以阅读:

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:


Boost版本的库已被广泛使用十
年。 Dinkumware版本的库,基于N1975
(相当于Boost库的版本2),附带Microsoft
Visual C ++ 2012。

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.

$ b为了说明使用,我修改了@Nayana Adassuriya的答案,稍作修改(OK,他忘了初始化一个变量,我使用 unsigned long long ,最重要的是使用:路径filePath(complete(dirIte-> path(),folderPath)); 调用其他函数)。我已经测试,它在Windows 7中工作良好。

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 <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; }
         }
      }
    }

int main()
{
    unsigned long long  f_size=0;
    getFoldersize("C:\\Silvio",f_size);
    cout << f_size << endl;
    system("pause");
    return 0;
}

这篇关于如何查找位于文件夹内的所有文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆