用C++写出本地计算机基本信息管理代码
时间: 2024-03-24 13:37:05 浏览: 53
以下是使用 C++ 编写获取本地计算机基本信息的示例代码:
```cpp
#include <iostream>
#include <windows.h>
#include <tchar.h>
#include <lmcons.h>
#pragma comment(lib, "netapi32.lib")
void getSystemInfo()
{
// 获取操作系统版本信息
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
std::cout << "操作系统版本:" << osvi.dwMajorVersion << "." << osvi.dwMinorVersion << "." << osvi.dwBuildNumber << std::endl;
// 获取计算机名称和用户名
TCHAR szComputerName[MAX_COMPUTERNAME_LENGTH + 1];
DWORD dwSize = sizeof(szComputerName) / sizeof(szComputerName[0]);
GetComputerName(szComputerName, &dwSize);
std::cout << "计算机名称:" << szComputerName << std::endl;
TCHAR szUserName[UNLEN + 1];
dwSize = sizeof(szUserName) / sizeof(szUserName[0]);
GetUserName(szUserName, &dwSize);
std::cout << "当前用户:" << szUserName << std::endl;
// 获取CPU信息
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
std::cout << "CPU核心数:" << sysInfo.dwNumberOfProcessors << std::endl;
// 获取内存信息
MEMORYSTATUSEX memInfo;
memInfo.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&memInfo);
std::cout << "物理内存总量:" << memInfo.ullTotalPhys / (1024 * 1024) << "MB" << std::endl;
std::cout << "可用物理内存:" << memInfo.ullAvailPhys / (1024 * 1024) << "MB" << std::endl;
// 获取硬盘信息
DWORD dwSize1, dwSize2;
TCHAR szVolumeName[MAX_PATH + 1], szFileSystem[MAX_PATH + 1];
DWORD dwSerialNumber, dwMaxComponentLen, dwFileSystemFlags;
GetVolumeInformation(_T("C:\\"), szVolumeName, MAX_PATH, &dwSerialNumber, &dwMaxComponentLen, &dwFileSystemFlags, szFileSystem, MAX_PATH);
ULARGE_INTEGER FreeBytesAvailable, TotalNumberOfBytes, TotalNumberOfFreeBytes;
GetDiskFreeSpaceEx(_T("C:\\"), &FreeBytesAvailable, &TotalNumberOfBytes, &TotalNumberOfFreeBytes);
std::cout << "硬盘总容量:" << TotalNumberOfBytes.QuadPart / (1024 * 1024 * 1024) << "GB" << std::endl;
std::cout << "可用空间:" << FreeBytesAvailable.QuadPart / (1024 * 1024 * 1024) << "GB" << std::endl;
}
int main()
{
getSystemInfo();
return 0;
}
```
这段代码可以获取操作系统版本、计算机名称、当前用户名、CPU核心数、物理内存总量、可用物理内存、硬盘总容量和可用空间等基本信息。请注意,在获取一些敏感信息时,比如用户名,应该谨慎处理,以免泄露用户隐私。
阅读全文