我有一些代码应该使用WriteFile
在文件中编写内容。要写入文件的内容类型为LPWSTR
,即wchar_t *
。该文件将写入ip
,ssl
和compression
。请考虑以下代码:
#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
,请更正我。感谢。
答案 0 :(得分:2)
您想使用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
。
旁注:如果你要从字符串文字中分配,你需要const版本的LPWSTR指针(LPCWSTR?我猜)