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

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

问题描述

中是否有任何 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++,你有 作为标准的 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:: 库,那么这个答案有点接近.如您所见,这里有一个文件系统库提案(修订版 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.

为了说明用法,我改编了@Nayana Adassuriya 的答案,做了很小的修改(好吧,他忘了初始化一个变量,我使用了unsigned long long,最重要的是使用:path 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天全站免登陆