获取文件版本(C++源码)
1、概述
有些场景要读取文件版本信息,详见代码
2、代码
2.1、调用示例
// 调用示例// 获取文件版本号FileVersion fileVersion;std::wstring path = L"C:\\Program Files\\Tencent\\Weixin\\4.1.1.19\\Weixin.dll";PathUtil::GetFileVersion(path, fileVersion);std::wcout << fileVersion.toString() << std::endl;
2.2、源码
头文件
#ifndef Path_Util_h_
#define Path_Util_h_ 1
#include <string>// 定义版本信息结构体
struct FileVersion
{int majorVersion = 0;int minorVersion = 0;int buildVersion = 0;int revisionVersion = 0;std::wstring toString() const;
};class PathUtil
{
public:static bool GetFileVersion(const std::wstring& path, FileVersion& fileVersion);
};#endif
源文件
#include "PathUtil.h"
#include <Windows.h>
#include <vector>#pragma comment(lib, "Version.lib")bool PathUtil::GetFileVersion(const std::wstring& path, FileVersion& fileVersion)
{if (path.empty()){return false;}DWORD dwSize = 0;dwSize = ::GetFileVersionInfoSize(path.c_str(), nullptr);if (dwSize == 0){return false;}std::vector<BYTE> buffer(dwSize);if (!::GetFileVersionInfo(path.c_str(), 0, dwSize, buffer.data())){return false;}VS_FIXEDFILEINFO* pFixedInfo = nullptr;UINT cbFixedInfo = 0;if (!::VerQueryValue(buffer.data(), L"\\", (LPVOID*)&pFixedInfo, &cbFixedInfo) || pFixedInfo == nullptr || cbFixedInfo == 0){return false;}// 0xfeef04bd 是Windows版本资源(Version Resource)中的一个固定签名值// 用于标识VS_FIXEDFILEINFO结构体的有效性if (pFixedInfo->dwSignature != 0xfeef04bd) {return false;}fileVersion.majorVersion = HIWORD(pFixedInfo->dwFileVersionMS);fileVersion.minorVersion = LOWORD(pFixedInfo->dwFileVersionMS);fileVersion.buildVersion = HIWORD(pFixedInfo->dwFileVersionLS);fileVersion.revisionVersion = LOWORD(pFixedInfo->dwFileVersionLS);return true;
}std::wstring FileVersion::toString() const
{wchar_t buf[64] = { 0 };swprintf_s(buf, _countof(buf), L"%d.%d.%d.%d", majorVersion, minorVersion, buildVersion, revisionVersion);return buf;
}