Thanks for the answers guys and here's how I implemented my GetDirectorySize() function...
Code:
BOOL MyGetFileSize (const TCHAR * szPath, ULONGLONG * ptrSize)
{
LARGE_INTEGER size;
HANDLE hFile;
hFile = CreateFile (szPath, 0, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
if (hFile != INVALID_HANDLE_VALUE) {
if (GetFileSizeEx (hFile, &size)) {
*ptrSize = size.QuadPart;
CloseHandle (hFile);
return TRUE;
} else {
CloseHandle (hFile);
return FALSE;
}
}
return FALSE;
}
// GetDirectorySize(), stores the directory size (in bytes) in 'ptrSize' and returns TRUE to indicate no error occurred
// or FALSE to indicate that something went wrong and the size might not be accurate
// WARNING: You need to append a '\' to the directory name before calling the function
BOOL GetDirectorySize (const TCHAR * szPath, ULONGLONG * ptrSize)
{
WIN32_FIND_DATA find;
BOOL returnCode = TRUE;
HANDLE hFind;
TCHAR * szFullPath = (TCHAR *) malloc ((MAX_PATH + 1)* sizeof (TCHAR));
// WARNING: You need to append a '\' to the directory name before calling the function
wsprintf (szFullPath, TEXT("%s*"), szPath);
hFind = FindFirstFile (szFullPath, &find);
if (hFind == INVALID_HANDLE_VALUE) {
return FALSE;
}
// Are we dealing with a directory
if (find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (lstrcmp (find.cFileName, TEXT(".")) && lstrcmp (find.cFileName, TEXT("..")))
{
size_t pos = lstrlen (find.cFileName) - 1;
if (find.cFileName[pos] != '\\') {
find.cFileName[pos+1] = '\\';
find.cFileName[pos+2] = 0;
}
wsprintf (szFullPath, TEXT("%s%s"), szPath, find.cFileName);
returnCode &= GetDirectorySize (szFullPath, ptrSize);
}
}
else // ... or are we dealing with a file
{
ULONGLONG fileSize = 0;
wsprintf (szFullPath, TEXT("%s%s"), szPath, find.cFileName);
if (MyGetFileSize (szFullPath, &fileSize))
*ptrSize = (*ptrSize) + fileSize;
else
returnCode = FALSE;
}
while (FindNextFile (hFind, &find))
{
// Are we dealing with a directory
if (find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (lstrcmp (find.cFileName, TEXT(".")) && lstrcmp (find.cFileName, TEXT("..")))
{
size_t pos = lstrlen (find.cFileName) - 1;
if (find.cFileName[pos] != L'\\') {
find.cFileName[pos+1] = L'\\';
find.cFileName[pos+2] = 0;
}
wsprintf (szFullPath, TEXT("%s%s"), szPath, find.cFileName);
returnCode &= GetDirectorySize (szFullPath, ptrSize);
}
}
else // ... or are we dealing with a file
{
ULONGLONG fileSize = 0;
wsprintf (szFullPath, TEXT("%s%s"), szPath, find.cFileName);
if (MyGetFileSize (szFullPath, &fileSize))
*ptrSize = (*ptrSize) + fileSize;
else
returnCode = FALSE;
}
}
if (GetLastError() != ERROR_NO_MORE_FILES)
returnCode = FALSE;
FindClose (hFind);
free (szFullPath);
return returnCode;
}