如何使用 c++ 在 txt 文件内部编写



我一直在尝试将硬件 id 插入一个名为 hardwareid2.txt 的文件内,这是我正在提取的硬件 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: %sn",     hwProfileInfo.szHwProfileGuid);
printf("Hardware Profile: %sn", hwProfileInfo.szHwProfileName);
}else{
return 0;
}
getchar();

}

在原始代码中

HW_PROFILE_INFO hwProfileInfo;
std::string hwid = hwProfileInfo.szHwProfileGuid;

hwProfileInfo的定义及其用于初始化hwid之间,明显不存在将系统配置文件加载到hwProfileInfo中的GetCurrentHwProfile调用。这意味着hwProfileInfo;处于默认状态,一大块零,因为它是在全局范围内声明的。szHwProfileGuid将是一个空的、立即以 null 结尾的字符串,并且该空将用于初始化hwid

很久以后,hwidfile <<hwid;会将空字符串写入文件流。printf("Hardware GUID: %sn", hwProfileInfo.szHwProfileGuid);打印正确的值,因为自使用空字符串初始化hwid以来hwProfileInfo该值已更新。

修复:摆脱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 failedn";
return -1;
}
// hwidfile.close(); don't need this. hwidfile will auto-close when it exists scope
printf("Hardware GUID: %sn",     hwProfileInfo.szHwProfileGuid);
printf("Hardware Profile: %sn", hwProfileInfo.szHwProfileName);
}
else
{
std::cout << "GetCurrentHwProfile failedn";
return -1;
}
getchar();
}

但是,如果我们确实需要它,则必须在成功获取 GUID 后对其进行更新GetCurrentHwProfile

blah blah blah...
if(GetCurrentHwProfile(&hwProfileInfo) != NULL)
{ 
hwid = hwProfileInfo.szHwProfileGuid;
std::ofstream hwidfile { "hardwareid2.txt" };
...blah blah blah

最新更新