c++中有没有获取指定文件夹大小的接口?
如果没有,我怎样才能得到一个文件夹的总大小,包括所有子文件夹和文件?
发布于 2013-03-19 14:06:08
实际上我不想使用任何第三方库。我只想用纯c++实现。
如果你使用MSVC++,你有 "as standard C++".,但是使用boost或MSVC -两者都是“纯C++”。
如果您不想使用boost,并且只想使用C++ std::库,那么这个答案有点接近。如您所见,。你可以在这里读到:
是该库的Boost版本,已经广泛使用了十年。该库的Dinkumware版本基于N1975 (相当于Boost库的版本2),随Microsoft Visual C++ 2012一起提供。
为了说明它的用法,我采用了@Nayana Adassuriya的答案,只做了很小的修改(好的,他忘记初始化一个变量,我使用unsigned long long
,最重要的是使用:path filePath(complete (dirIte->path(), folderPath));
在调用其他函数之前恢复完整路径)。我已经测试过了,它在windows7上运行得很好。
#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;
}
发布于 2013-03-19 11:14:30
让操作系统为你做这件事怎么样:
long long int getFolderSize(string path)
{
// command to be executed
std::string cmd("du -sb ");
cmd.append(path);
cmd.append(" | cut -f1 2>&1");
// execute above command and get the output
FILE *stream = popen(cmd.c_str(), "r");
if (stream) {
const int max_size = 256;
char readbuf[max_size];
if (fgets(readbuf, max_size, stream) != NULL) {
return atoll(readbuf);
}
pclose(stream);
}
// return error val
return -1;
}
发布于 2013-03-19 10:36:43
你可以这样使用boost。您可以尝试对其进行更深层次的优化。
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
namespace bsfs = boost::filesystem;
void getFoldersize(string rootFolder,long & file_size){
boost::replace_all(rootFolder, "\\\\", "\\");
bsfs::path folderPath(rootFolder);
if (bsfs::exists(folderPath)){
bsfs::directory_iterator end_itr;
for (bsfs::directory_iterator dirIte(rootFolder); dirIte != end_itr; ++dirIte )
{
bsfs::path filePath(dirIte->path());
try{
if (!bsfs::is_directory(dirIte->status()) )
{
file_size = file_size + bsfs::file_size(filePath);
}else{
getFoldersize(filePath.string(),file_size);
}
}catch(exception& e){
cout << e.what() << endl;
}
}
}
}
int main(){
long file_size =0;
getFoldersize("C:\\logs",file_size);
cout << file_size << endl;
system("pause");
return 0;
}
https://stackoverflow.com/questions/15495756
复制相似问题