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;
}
这篇关于如何找到位于文件夹内的所有文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何找到位于文件夹内的所有文件的大小?
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
