skip to Main Content

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;

}

2

Answers


  1. Try it with

    int inputBufferSize = inputString.size() + 1;
    

    The +1 is for the null terminator

    Login or Signup to reply.
  2. 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 () at the end, and you should allocate space for it. Specifically, replace char* inputBuffer = new char[inputBufferSize]; with char* inputBuffer = new char[inputBufferSize+1];.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search