How can I find the size of all files located inside a folder?(如何找到位于文件夹内的所有文件的大小?)
问题描述
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++,你有
作为标准的 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;
}
这篇关于如何找到位于文件夹内的所有文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何找到位于文件夹内的所有文件的大小?


- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01