获取exe版本号

-
-
2025-09-26 11:01
#include 
#include 

#ifdef _WIN32
#include 
#else
#include 
#include 
#endif

std::string getExeFileVersion(const std::string& filePath)
{
   std::string version;

#ifdef _WIN32
   DWORD handle;
   DWORD infoSize = GetFileVersionInfoSizeA(filePath.c_str(), &handle);
   if (infoSize > 0) {
       std::vector buffer(infoSize);
       if (GetFileVersionInfoA(filePath.c_str(), handle, infoSize, buffer.data())) {
           VS_FIXEDFILEINFO* fileInfo;
           UINT fileInfoSize;
           if (VerQueryValueA(buffer.data(), "\\", (LPVOID*)&fileInfo, &fileInfoSize)) {
               unsigned int major = (fileInfo->dwFileVersionMS >> 16) & 0xffff;
               unsigned int minor = (fileInfo->dwFileVersionMS) & 0xffff;
               unsigned int patch = (fileInfo->dwFileVersionLS >> 16) & 0xffff;
               unsigned int build = (fileInfo->dwFileVersionLS) & 0xffff;

               version = std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(patch) + "." + std::to_string(build);
           }
       }
   }
#elif defined(__linux__)
   // 在Linux平台,可以使用命令行工具"readelf"来获取可执行文件的版本号
   std::string command = "readelf -p .comment " + filePath;
   FILE* pipe = popen(command.c_str(), "r");
   if (pipe) {
       char buffer[128];
       std::string result;
       while (!feof(pipe)) {
           if (fgets(buffer, 128, pipe) != nullptr) {
               result += buffer;
           }
       }
       pclose(pipe);

       size_t pos = result.find("GCC:");
       if (pos != std::string::npos) {
           size_t startPos = pos + 4;
           size_t endPos = result.find_first_of("\n", startPos);
           version = result.substr(startPos, endPos - startPos);
       }
   }
#endif

   return version;
}

int main()
{
   std::string exeFilePath = "path/to/exe/file";
   std::string version = getExeFileVersion(exeFilePath);
   std::cout << "Exe file version: " << version << std::endl;

   return 0;
}


清遥
遥夜泛清瑟,西风生翠萝。
微博热搜榜Top10

加载中...
最新评论

加载中...