This shows how to get the size of all the files in a folder, and all its sub-folders on MS-Windows operating system. It uses recursion to transverse all the directories, and return a 64-bit integer. It was compiled with VC++ 2008 Express and Code::Blocks Version 8.02 with MinGW compiler.
How to get size of all files in a directory
Excizted commented: Useful code snippet. +1
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
__int64 TransverseDirectory(string path)
{
WIN32_FIND_DATA data;
__int64 size = 0;
string fname = path + "\\*.*";
HANDLE h = FindFirstFile(fname.c_str(),&data);
if(h != INVALID_HANDLE_VALUE)
{
do {
if( (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
{
// make sure we skip "." and "..". Have to use strcmp here because
// some file names can start with a dot, so just testing for the
// first dot is not suffient.
if( strcmp(data.cFileName,".") != 0 &&strcmp(data.cFileName,"..") != 0)
{
// We found a sub-directory, so get the files in it too
fname = path + "\\" + data.cFileName;
// recurrsion here!
size += TransverseDirectory(fname);
}
}
else
{
LARGE_INTEGER sz;
// All we want here is the file size. Since file sizes can be larger
// than 2 gig, the size is reported as two DWORD objects. Below we
// combine them to make one 64-bit integer.
sz.LowPart = data.nFileSizeLow;
sz.HighPart = data.nFileSizeHigh;
size += sz.QuadPart;
}
}while( FindNextFile(h,&data) != 0);
FindClose(h);
}
return size;
}
int main(int argc, char* argv[])
{
__int64 size = 0;
string path;
size = TransverseDirectory("c:\\dvlp");
cout << "\n\nDirectory Size = " << size << "\n";
cin.ignore();
return 0;
}
Excizted 67 Posting Whiz
Rajesh R Subram 127 Junior Poster in Training
Ancient Dragon commented: I had not noticed it -- thanks. +25
marco93 -87 Junior Poster
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster
Rajesh R Subram 127 Junior Poster in Training
nezachem 616 Practically a Posting Shark
Ancient Dragon commented: good points in those links. :) +25
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.