#include<Windows.h>
#include<iostream>
#include<tchar.h>
using namespace std;
bool GetSize1(LPCTSTR filepath)//方法一,主要使用GetFileSize这个API函数
{
HANDLE hFile = CreateFile(filepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
MessageBox(NULL, _T("文件打开失败!"), _T("Tip"), MB_OK);
CloseHandle(hFile);
return false;
}
else
{
DWORD fileHigh = 0; //当文件大小大于4GB时,就需要用到高32位
DWORD fileSize = GetFileSize(hFile, &fileHigh);
LONGLONG lFileSize = (((LONGLONG)fileHigh) << 32) | fileSize; //两个32位变量结合为一个64位变量
//将32位变量转换为64位变量,然后左移32位成为高32位,最后于与一个32位变量相或,构成一个64位变量
TCHAR sFileSize[256] = { 0 };
swprintf_s(sFileSize, _T("该文件的大小是:%lld字节"), lFileSize);
MessageBox(NULL, sFileSize, _T("Tip"), MB_OK);
CloseHandle(hFile);
return true;
}
}
bool GetSize2(LPCTSTR filepath)//方法二,主要使用GetFileSizeEx这个GetFileSize函数的扩展函数
{
HANDLE hFile = CreateFile(filepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
MessageBox(NULL, _T("文件打开失败!"), _T("Tip"), MB_OK);
CloseHandle(hFile);
return false;
}
else
{
LARGE_INTEGER lpfileSize = { 0 };
BOOL file = GetFileSizeEx(hFile, &lpfileSize);
if (file)
{
TCHAR sFileSize[256] = { 0 };
swprintf_s(sFileSize, _T("该文件的大小是:%lld字节"), lpfileSize.QuadPart);
MessageBox(NULL, sFileSize, _T("Tip"), MB_OK);
CloseHandle(hFile);
}
else
CloseHandle(hFile);
return true;
}
}
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hpreInstance, LPTSTR lpCmdLine, INT nShowCmd)
{
//GetSize1(lpCmdLine);
GetSize2(lpCmdLine);
return 0;
}
Windows编程之获取文件大小
最新推荐文章于 2024-09-13 11:19:47 发布