我一直在尝试在名为 hardwareid2.txt 的文件中插入硬件 ID,这是我要提取的硬件 ID 应该插入的位置,但它似乎没有这样做,我不知道为什么,所有代码似乎在做的是创建文件而不是在文件内部写入。有人可以帮我调试吗?
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
HW_PROFILE_INFO hwProfileInfo;
std::string hwid = hwProfileInfo.szHwProfileGuid;
int main()
{
if(GetCurrentHwProfile(&hwProfileInfo) != NULL){
std::ofstream hwidfile { "hardwareid2.txt" };
hwidfile.open("hardwareid2.txt");
hwidfile <<hwid;
hwidfile.close();
printf("Hardware GUID: %s\n", hwProfileInfo.szHwProfileGuid);
printf("Hardware Profile: %s\n", hwProfileInfo.szHwProfileName);
}else{
return 0;
}
getchar();
}
在原始代码中
HW_PROFILE_INFO hwProfileInfo;
std::string hwid = hwProfileInfo.szHwProfileGuid;
GetCurrentHwProfile
将系统配置文件加载到其中的调用在定义和初始化的用法hwProfileInfo
之间明显不存在。这意味着它处于默认状态,一大块零,因为它是在全局范围内声明的。将是一个空的、立即以 null 结尾的字符串,并且该空将用于初始化.hwProfileInfo
hwid
hwProfileInfo;
szHwProfileGuid
hwid
很久以后hwidfile <<hwid;
会将空字符串写入文件流。printf("Hardware GUID: %s\n", hwProfileInfo.szHwProfileGuid);
打印正确的值,因为自使用空字符串初始化后hwProfileInfo
已更新。hwid
修复:摆脱hwid
. 我们不需要它。
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
HW_PROFILE_INFO hwProfileInfo; // unless we have a very good reason, this should
// not be global
if(GetCurrentHwProfile(&hwProfileInfo) != NULL)
{ // update info was a success. NOW we have a GUID and can do stuff with
// hwProfileInfo
std::ofstream hwidfile { "hardwareid2.txt" };
hwidfile.open("hardwareid2.txt");
if (!(hwidfile << hwProfileInfo.szHwProfileGuid))
{ // will fail if can't write for any reason, like file didn't open
std::cout << "File write failed\n";
return -1;
}
// hwidfile.close(); don't need this. hwidfile will auto-close when it exists scope
printf("Hardware GUID: %s\n", hwProfileInfo.szHwProfileGuid);
printf("Hardware Profile: %s\n", hwProfileInfo.szHwProfileName);
}
else
{
std::cout << "GetCurrentHwProfile failed\n";
return -1;
}
getchar();
}
但如果我们确实需要它,必须在成功获取 GUID 后更新它GetCurrentHwProfile
blah blah blah...
if(GetCurrentHwProfile(&hwProfileInfo) != NULL)
{
hwid = hwProfileInfo.szHwProfileGuid;
std::ofstream hwidfile { "hardwareid2.txt" };
...blah blah blah
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句