C++(or Visual Studio) saving the file will not preserve the original file contents

55 Views Asked by At

I'm new to server-side development, but I know a lot of things from front-end development

My problem:

1. From the client side (React.js application), a JSON string is sent (POST request) to a C++ server:

  const handleFetchData = async () => {
    try {
      dispatch(setRepoUrl(inputUrl))
      const urlParts = inputUrl.split('/')
      const username = urlParts[3]
      const repo = urlParts[4]
      const response = await axios.get(
        `https://api.github.com/repos/${username}/${repo}/issues`
      )
      dispatch(setIssues(response.data))

      const api_data = JSON.stringify(response.data)

      await axios.post('http://127.0.0.1:5174/user_data.json', { api_data })
      console.log('Data saved on server:', api_data)
    } catch (error) {
      console.error('Error fetching data: ', error)
    }
  }

2. The C++ server processes this request and writes it to a file, but first deletes existing data in the .json file:

    void TcpServer::writeData(const std::string& data)
    {
        remove(user_data_path);
        size_t start = data.find("{");
        if (start == std::string::npos)
        {
            std::cerr << "JSON data not found in the input string.\n\n" << std::endl;
            return;
        }

        std::string jsonData = data.substr(start);

        std::ofstream file(user_data_path, std::ios::out);
        if (file.is_open())
        {
            file << jsonData << std::endl;
            file.close();
            std::cout << "Data saved to user_data.json\n\n" << std::endl;
        }
        else
        {
            std::cerr << "Failed to open file for writing.\n\n" << std::endl;
        }
    }

3. After writing the JSON string to the .json file, the Visual Studio application displays a window with the following error message:
File Load
Some bytes have been replaced with the Unicode substitution character while loading file
Saving the file will not preserve the original file contents
enter image description here

4. After that, some characters in the JSON string are transformed into this - (\r\n\t\t<Ex1 innerRef={ref}>\r\n\t\t\t{children}\r\n\t\t</Ex1>\r\n\t);\r\n});���������������������������������7#�

Perhaps someone knows what the problem is and how to fix it.
In the end, I need a valid JSON string.

P.S. This server is written for Windows (#include <winsock.h>).
I don't want to provoke dissatisfaction in the comments like "why is he writing a server in C++ instead of node.js, etc."
I am a Junior Front-end Developer, and I just like C++, so I chose this language.
Thank you for understanding, I hope for your help.

I've been searching for a solution to the problem for a long time and simply came to the conclusion to write a post on Stack Overflow, so I don't have any versions of the solution to this problem.

1

There are 1 best solutions below

1
frozzen_alacrity On

The problem was the buffer size which was 30720 bytes.

const int BUFFER_SIZE = 500000000;

I just changed the size which is approximately 500MB and now select them from the heap.

char* buffer = new char[BUFFER_SIZE];

This is where the buffer is used, I simply take data from it and then pass it as an argument to a function that writes this data to a file:

void TcpServer::startListen()
{
   if (listen(m_socket, 20) < 0)
   {
       exitWithError("Socket listen failed");
   }

   std::ostringstream ss;
   ss << "\n*** Listening on ADDRESS: " << inet_ntoa(m_socketAddress.sin_addr) << " PORT: " << ntohs(m_socketAddress.sin_port) << " ***\n\n";
   log(ss.str());

   int bytesReceived;

   while (true)
   {
       log("====== Waiting for a new connection ======\n\n\n");
       acceptConnection(m_new_socket);

       char* buffer = new char[BUFFER_SIZE];

       bytesReceived = recv(m_new_socket, buffer, BUFFER_SIZE, 0);
       if (bytesReceived < 0)
       {
           exitWithError("Failed to receive bytes from client socket connection");
       }

       std::ostringstream ss;
       ss << "------ Received Request from client ------\n\n";
       log(ss.str());

       sendResponse();

       std::string requestData(buffer);
       handleRequest(requestData);

       delete[] buffer;
       closesocket(m_new_socket);
   }

}

The data was written to the file as needed because the buffer size could not accommodate large data.