c,#include,int main() {, printf("Version: %s,", OPENSSL_VERSION_TEXT);, return 0;,},
“
在C语言编程中,获取版本号是一个常见需求,无论是操作系统的版本号还是应用程序自身的版本号,下面将详细介绍如何在C语言中通过API来获取这些版本号,并提供相应的示例代码。
不同的操作系统提供了不同的API来获取其版本号,以下是Windows、MacOS和Linux系统下获取操作系统版本号的方法:
1、Windows
使用GetVersionEx函数:此函数可以获取Windows操作系统的主版本号和次版本号等信息,需要注意的是,从Windows 8.1开始,微软建议使用其他方法来检测操作系统版本,因为GetVersionEx可能返回不准确的信息。
示例代码:
#include <windows.h> #include <stdio.h> int main() { OSVERSIONINFO osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!GetVersionEx(&osvi)) { printf("Call to GetVersionEx failed! "); return 1; } printf("Major version: %ld ", osvi.dwMajorVersion); printf("Minor version: %ld ", osvi.dwMinorVersion); printf("Build number: %ld ", osvi.dwBuildNumber); return 0; }
2、MacOS
使用Gestalt函数:此函数可以返回一个包含了操作系统版本信息的结构体,开发者可以通过读取这些信息来获取到精确的操作系统版本号。
示例代码:
#include <CoreServices/CoreServices.h> #include <stdio.h> int main() { NSDictionary* systemInfo = (NSDictionary*)Gestalt(gestaltSystemVersionInfo); if (systemInfo == NULL) { printf("Failed to get system info "); return 1; } NSString* osVersion = (NSString*)CFDictionaryGetValue(systemInfo, CFSTR("ProductVersion")); char version[256]; if (![osVersion getCString:version maxLength:sizeof(version) encoding:kCFStringEncodingASCII]) { printf("Failed to convert version string "); return 1; } printf("OS Version: %s ", version); return 0; }
3、Linux
读取/etc/os-release文件:大多数Linux发行版都会在这个文件中记录操作系统的版本号,可以通过读取这个文件来获取到操作系统的版本号。
示例代码:
#include <stdio.h> #include <stdlib.h> int main() { FILE* file = fopen("/etc/os-release", "r"); if (file == NULL) { perror("Failed to open /etc/os-release"); return 1; } char line[256]; while (fgets(line, sizeof(line), file)) { if (strncmp(line, "PRETTY_NAME=", 11) == 0) { char* version = line + 11; // Remove quotes if present if (version[0] == '"') { version++; char* end = strchr(version, '"'); if (end) { *end = '