我如何用 C++ 在 txt 文件中写入

How do i write inside of a txt file with c++

我一直在尝试将硬件 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: %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 调用 GetCurrentHwProfile 会将系统配置文件加载到 hwProfileInfo 中,在 hwProfileInfo 的定义及其初始化 hwid 的用法之间明显不存在。这意味着 hwProfileInfo; 处于默认状态,一大块零,因为它是在全局范围内声明的。 szHwProfileGuid 将是一个空字符串,立即 null-terminated 字符串,该空字符串将用于初始化 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();
}

但是如果我们确实需要它,它必须在GetCurrentHwProfile

成功获取GUID后更新
blah blah blah...
    if(GetCurrentHwProfile(&hwProfileInfo) != NULL)
    { 
        hwid = hwProfileInfo.szHwProfileGuid;
        std::ofstream hwidfile { "hardwareid2.txt" };
...blah blah blah