繁体   English   中英

如何使用 C++ 在 txt 文件中写入内容

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

我一直在尝试在名为 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;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM