0

I need to load a JSON file and copy it into a string buffer but it is failing to open the file. What could be the problem, can I use any other method?

My JSON file is as follows:


{
  "ip": [ "212.253.144.10","192.32.12.1","192.12.1.1"]
}

and the code:


#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
void CMFCJasonDlg::OnBnClickedButton2()

{

    ifstream inputFile("C:\\Users\\hp\\Desktop\\VK\\ip.json");
    if (!inputFile.is_open())
    {
        MessageBox(L"Failed to open file", 0, 0);
        CloseHandle(hdevice);
        return; 
    }
    
    stringstream buffer;
    buffer << inputFile.rdbuf();
    string inputString = buffer.str();
    inputFile.close();
    
    DWORD inputBufferSize = sizeof(inputString);
    char* inputBuffer = new char[inputBufferSize];
    strncpy_s(inputBuffer, inputBufferSize, inputString.c_str(), inputString.size());
    
    delete[] inputBuffer;

}
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
vk_
  • 35
  • 4
  • I have even tried open json file in project and use " ifstream inputFile("ip.json");" – vk_ Feb 27 '23 at 08:31
  • In C there is `perror` function to print more information about last error. Should work for C++, too. – Gerhardh Feb 27 '23 at 08:33
  • `sizeof(inputString)` returns the size of the `std::string` data type, but has nothing to do with the length/size of the string it holds. – t.niese Feb 27 '23 at 08:44
  • A side note: [using namespace std](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – wohlstad Feb 27 '23 at 12:59

2 Answers2

0

Try it with

int inputBufferSize = inputString.size() + 1;

The +1 is for the null terminator

muhmann
  • 191
  • 9
0

Your code has two problem:

First, sizeof(inputString) returns the size of the variable inputString, which has nothing to do with its length. You should use inputString.length() to obtain the length.

Second, every string stored in a byte array is terminated by a null terminator (\0) at the end, and you should allocate space for it. Specifically, replace char* inputBuffer = new char[inputBufferSize]; with char* inputBuffer = new char[inputBufferSize+1];.

intlsy
  • 821
  • 4
  • 7