// ConsoleApplication10.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <string>
#include <strsafe.h>
#pragma comment(lib, "User32.lib")
void DisplayErrorBox(LPTSTR lpszFunction);
LARGE_INTEGER GetDirectorySize(TCHAR* szDir);
int _tmain(int argc, TCHAR *argv[])
{
LARGE_INTEGER diretorySize;
diretorySize.QuadPart = 0;
TCHAR szDir[MAX_PATH];
size_t length_of_arg;
DWORD dwError = 0;
//if (argc != 2)
//{
// _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
// return (-1);
//}
std::string path = "D:\\IhpClient_kylin\\Project\\bin";
StringCchLength(path.c_str(), MAX_PATH, &length_of_arg);
if (length_of_arg > (MAX_PATH - 3))
{
_tprintf(TEXT("\nDirectory path is too long.\n"));
return (-1);
}
_tprintf(TEXT("\nTarget directory is %s\n\n"), path.c_str());
StringCchCopy(szDir, MAX_PATH, path.c_str());
diretorySize = GetDirectorySize(szDir);
_tprintf(TEXT("directory Size %lld bytes\n"), diretorySize.QuadPart);
return dwError;
}
void DisplayErrorBox(LPTSTR lpszFunction)
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf,
0, NULL);
// Display the error message and clean up
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
LARGE_INTEGER GetDirectorySize(TCHAR* szDir)
{
WIN32_FIND_DATA ffd;
LARGE_INTEGER diretorySize;
diretorySize.QuadPart = 0;
HANDLE hFind = INVALID_HANDLE_VALUE;
DWORD dwError = 0;
TCHAR szDirAll[MAX_PATH];
StringCchCopy(szDirAll, MAX_PATH, szDir);
StringCchCat(szDirAll, MAX_PATH, TEXT("\\*"));
hFind = FindFirstFile(szDirAll, &ffd);
if (INVALID_HANDLE_VALUE == hFind)
{
DisplayErrorBox(TEXT("FindFirstFile"));
return diretorySize;
}
do
{
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (strcmp((char*)ffd.cFileName, ".") == 0 || strcmp((char*)ffd.cFileName, "..") == 0)
{
//过滤当前目录和上一层目录
continue;
}
TCHAR szSubDir[MAX_PATH];
StringCchCopy(szSubDir, MAX_PATH, szDir);
StringCchCat(szSubDir, MAX_PATH, TEXT("\\"));
StringCchCat(szSubDir, MAX_PATH, ffd.cFileName);
LARGE_INTEGER subDirSize = GetDirectorySize(szSubDir);
diretorySize.QuadPart += subDirSize.QuadPart;
}
else
{
diretorySize.QuadPart += ffd.nFileSizeLow + ffd.nFileSizeHigh;
}
} while (FindNextFile(hFind, &ffd) != 0);
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES)
{
DisplayErrorBox(TEXT("FindFirstFile"));
}
FindClose(hFind);
return diretorySize;
}
windows获取文件夹大小
于 2023-03-17 16:24:49 首次发布