イネマルのプログラミング備忘録

趣味プログラマのメモ

Windows C++ 実行ファイルからバージョン情報を取得する

メモ

バージョンリソースが含まれるファイルからバージョン情報を取得する方法。
Windows API の GetFileVersionInfo を使って取得する。

実装

#include <windows.h>
#include <iostream>
#include <vector>
#include <string>

#pragma comment(lib, "version.lib")

// バージョン取得用の構造体
struct Version final {
    WORD minor;
    WORD major;
    WORD revision;
    WORD build;
};

// バージョン取得関数
bool GetFileVersion(const std::string& path, Version& version)
{
    DWORD infoHandle = 0;
    const auto size = GetFileVersionInfoSizeA(path.c_str(), &infoHandle);
    std::vector<char> buffer(size);
    if (buffer.empty()) {
        return false;
    }
    else if (GetFileVersionInfoA(path.c_str(), infoHandle, size, buffer.data()) == 0) {
        return false;
    }
    VS_FIXEDFILEINFO* pInfo;
    UINT verLen;
    if (VerQueryValueA(buffer.data(), "\\", reinterpret_cast<LPVOID*>(&pInfo), &verLen) == 0) {
        return false;
    }
    union {
        struct {
            DWORD fileVersionMS;
            DWORD fileVersionLS;
        };
        Version info;
    } ver = { pInfo->dwFileVersionMS, pInfo->dwFileVersionLS };
    version = ver.info;
    return true;
}

int main()
{
    const char* filePath = R"(C:\Windows\System32\notepad.exe)";

    // バージョン取得
    Version ver = {};
    if (GetFileVersion(filePath, ver)) {
        std::cout << "Major:" << ver.major << std::endl;
        std::cout << "Minor:" << ver.minor << std::endl;
        std::cout << "Build:" << ver.build << std::endl;
        std::cout << "Revision:" << ver.revision << std::endl;
    }
    else {
        std::cout << "エラー" << std::endl;
    }

    system("pause");
    return 0;
}

以上。