gpt4 book ai didi

c++ - Boost Property Tree Json 读取包含 LPWSTR 的文件

转载 作者:太空狗 更新时间:2023-10-29 21:41:20 25 4
gpt4 key购买 nike

我有一些代码应该使用 WriteFile 将内容写入文件。写入文件的内容类型为LPWSTRwchar_t *。该文件将写入ipsslcompression。考虑以下代码:

#include <Windows.h>
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
int main()
{
LPWSTR ip = NULL;
LPWSTR ssl = NULL;
LPWSTR comp = NULL;
wchar_t buffer[300];
HANDLE hFile;
BOOL bErrorFlag;
DWORD dwBytesToWrite = 0; //(DWORD)strlen(buffer);
DWORD dwBytesWritten = 0;

if(ip == NULL || wcslen(ip) == 0 )
{
ip = L"127.0.0.1";
}

if(ssl == NULL || wcslen(ssl) == 0)
{
ssl = L"False";
}

if(comp == NULL || wcslen(comp) == 0 )
{
comp = L"True";
}


wsprintf(buffer, L"{\n\"ip\": \"%ls\",\n\"ssl\": \"%ls\",\n\"compression\":\"%ls\"\n}",ip,ssl,comp);
//swprintf(buffer, 150, L"{\n\"ipaddress\": \"%ls\",\n\"ssl\": \"%ls\",\n\"compression\":\"%ls\"\n}",ip,ssl,comp);
std::wcout << buffer << std::endl;
dwBytesToWrite = (wcslen(buffer)) * sizeof(wchar_t);

hFile = CreateFile(L"C://SomeFolder//some_config.config", // name of the write
GENERIC_WRITE, // open for writing
0, // do not share
NULL, // default security
CREATE_ALWAYS, // always create new file
FILE_ATTRIBUTE_NORMAL, // normal file
NULL);

bErrorFlag = WriteFile(
hFile, // open file handle
buffer, // start of data to write
dwBytesToWrite, // number of bytes to write
&dwBytesWritten, // number of bytes that were written
NULL); // no overlapped structure

CloseHandle(hFile);
boost::property_tree::ptree pt;
try
{
boost::property_tree::read_json("C://SomeFolder//some_config.config", pt);
}
catch(std::exception &e)
{
std::cout << e.what();
}
try
{
std::cout << pt.get<std::string>("ip");
}
catch(std::exception &e)
{
std::cout << e.what();
}
}

文件内容会有

{
"ip": "127.0.0.1",
"ssl": "False",
"compression":"True"
}

但是使用 read_json 失败并给出错误:

C://SomeFolder//some_config.config(1): expected object name 
No such node (ip)

代码有什么问题?为什么 read_json 不能读取写入的文件?如果我错误地使用了 WriteFile,请纠正我。谢谢。

最佳答案

你想使用wptree:

boost::property_tree::wptree pt;
boost::property_tree::read_json("C://SomeFolder//some_config.config", pt);
std::wcout << pt.get<std::wstring>(L"ip");

还要注意那里的 L"ip"wstring

旁注:如果从字符串字面量赋值,则需要 LPWSTR 指针(LPCWSTR?我猜)的 const 版本

关于c++ - Boost Property Tree Json 读取包含 LPWSTR 的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29091835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com