本例用MFC写的,但是所有API都是WindowsAPI,字符转化一下就好。
获取文件大小
CString FileSize(CString strFilePath)
{
CString strFileSize;
HANDLE hFile = CreateFile(strFilePath, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return strFileSize;
}
//获取文件大小
__int64 iFileSize = GetFileSize(hFile, NULL);
TCHAR szFileSize[MAX_PATH];
StrFormatByteSize(iFileSize, szFileSize, MAX_PATH);
strFileSize = szFileSize;
return strFileSize;
}
文件最后修改时间
void FileTimeToTime_t(FILETIME ft, time_t *t)
{
LONGLONG ll;
ULARGE_INTEGER ui;
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
ll = ft.dwHighDateTime << 32 + ft.dwLowDateTime;
*t = ((LONGLONG)(ui.QuadPart - 116444736000000000) / 10000000);
}
time_t FileSize(CString strFilePath)
{
WIN32_FIND_DATAW wfd;
HANDLE handlePath = NULL;
handlePath = FindFirstFileW(strFilePath.GetString(), &wfd);
time_t * tWriteTime;
FileTimeToTime_t(wfd.ftLastWriteTime, tWriteTime);
if (handlePath != NULL)
{
FindClose(handlePath);
}
return tWriteTime;
}
文件版本号
头文件
#include <windows.h>
#pragma comment(lib,"Version.lib")
MFC:
CString GetFileVersion(CString FileNamePath)
{
CString FileVersions;
VS_FIXEDFILEINFO *pVsInfo;
unsigned int iFileInfoSize = sizeof(VS_FIXEDFILEINFO);
int iVerInfoSize = GetFileVersionInfoSizeW(FileNamePath.GetString(), NULL);
if(iVerInfoSize != 0)
{
wchar_t *pBuf = NULL;
while(!pBuf)
{
pBuf = new wchar_t[iVerInfoSize];
}
if(GetFileVersionInfoW(FileNamePath.GetString(), 0, iVerInfoSize, pBuf))
{
if(VerQueryValueW(pBuf, L"\\", (void **)&pVsInfo, &iFileInfoSize))
{
FileVersions.Format(L"%d.%d.%d.%d", HIWORD(pVsInfo->dwFileVersionMS), LOWORD(pVsInfo->dwFileVersionMS), HIWORD(pVsInfo->dwFileVersionLS), LOWORD(pVsInfo->dwFileVersionLS));
}
}
delete pBuf;
}
return FileVersions;
}
C++:
BOOL GetSoftWareVersion(wstring &wstrVersion)
{
wstring FileNamePath;
wchar_t szVersion[1024];
VS_FIXEDFILEINFO *pVsInfo;
unsigned int iFileInfoSize = sizeof(VS_FIXEDFILEINFO);
int iVerInfoSize = GetFileVersionInfoSizeW(FileNamePath.c_str(), NULL);
if(iVerInfoSize != 0)
{
wchar_t *pBuf = NULL;
while(!pBuf)
{
pBuf = new wchar_t[iVerInfoSize];
}
if(GetFileVersionInfoW(FileNamePath.c_str(), 0, iVerInfoSize, pBuf))
{
if(VerQueryValueW(pBuf, L"\\", (void **)&pVsInfo, &iFileInfoSize))
{
//FileVersions.Format(L"%d.%d.%d.%d", HIWORD(pVsInfo->dwFileVersionMS), LOWORD(pVsInfo->dwFileVersionMS), HIWORD(pVsInfo->dwFileVersionLS), LOWORD(pVsInfo->dwFileVersionLS));
_snwprintf(szVersion, sizeof(szVersion), L"%d.%d.%d.%d", HIWORD(pVsInfo->dwFileVersionMS), LOWORD(pVsInfo->dwFileVersionMS), HIWORD(pVsInfo->dwFileVersionLS), LOWORD(pVsInfo->dwFileVersionLS));
wstrVersion = szVersion;
}
}
delete pBuf;
}
return TRUE;
}
获取自身文件路径
//获取当前路径
TCHAR szPath[MAX_PATH];
GetModuleFileNameW(NULL, szPath, MAX_PATH);
wstring FileNamePath = szPath; //全路径
if (FileNamePath.empty())
{
return FALSE;
}
int iSize = FileNamePath.find_last_of('\\');
FileNamePath = FileNamePath.substr(0, iSize + 1); //不带文件名路径