您的位置:首页 > 其它

获取文件占用空间大小

2013-12-20 13:52 381 查看
UINT64 GetFileSpaceSize( const string &filePath )

{

USES_CONVERSION;

TCHAR *szFileName = A2T(filePath.c_str());

HANDLE hFile = ::CreateFile(szFileName, GENERIC_READ | FILE_SHARE_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

if (hFile == INVALID_HANDLE_VALUE)

{

_tprintf_s(_T("Failed to create file handle: %s ! error code:%d\n"), szFileName, GetLastError());

return -1;

}

UINT64 uFileSize = 0;

::GetFileSizeEx(hFile, (PLARGE_INTEGER)&uFileSize);

::CloseHandle(hFile);

// 获取磁盘根路径

TCHAR szVolumePathName[] = _T("C:\\");

::GetVolumePathName(szFileName, szVolumePathName, sizeof(szVolumePathName) / sizeof(TCHAR));

// 保存簇信息的变量

DWORD dwSectorsPerCluster = 0;

DWORD dwBytesPerSector = 0;

DWORD dwNumberOfFreeClusters = 0;

DWORD dwTotalNumberOfClusters = 0;

// 获取簇信息

if (!::GetDiskFreeSpace(szVolumePathName, //磁盘根路径

&dwSectorsPerCluster, //每簇的扇区数

&dwBytesPerSector, //每扇区的字节数

&dwNumberOfFreeClusters, //空余簇的数量

&dwTotalNumberOfClusters //全部簇的数量

))

{

_tprintf_s(_T("Failed to get disk cluster info! error code: %d\n"), GetLastError());

return -1;

}

// 簇大小 = 每簇的扇区数 * 每扇区的字节数

DWORD dwClusterSize = dwSectorsPerCluster * dwBytesPerSector;

UINT64 dwFileSpaceSize = (UINT64)(ceil(uFileSize / (double)dwClusterSize) * dwClusterSize);

return dwFileSpaceSize;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: