lundi 16 mars 2015

Boost Property Tree Json Read for file containing LPWSTR


I have some code that is supposed to write the content in file using WriteFile. The type of contents to be written in file are LPWSTR ie wchar_t *. The file will write ip, ssl and compression. Consider the following code:



#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();
}
}


The contents of the file will have



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


But using read_json fails and gives error:



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


What is wrong in the code? Why can't the read_json reads the file written? If I am using WriteFile incorrectly, please correct me. Thanks.




Aucun commentaire:

Enregistrer un commentaire