Read and write to one fstream file

I want to update an existing json file.

This is an example json file:

{
   "Foo": 51.32,
   "Number": 100,
   "Test": "Test1"
}

Logs from the program:

Operation successfully performed
100
"Test1"
51.32
46.32
Done

It seems that everythink works as expected ...

If I change fstream to ifstream to read, and then from the stream to write it, working ...

I tried using a debugger, and as I see it, I have incorrect data in the basic_ostream object ... but I don’t know why, I am using data from a row with corrected (updated data). Any idea what is wrong :-)?

+4
source share
1 answer

You have a few problems here.

json json_data(fs); , EOF. , .

-, . , :

if (fs.is_open())
{
    json json_data(fs); // reads to end of file
    fs.clear(); // clear flag
    fs.seekg(0); // move to beginning

, , , , , , , :

    std::cout << "Operation successfully performed\n";
    std::cout << json_data.at("Number") << std::endl;
    std::cout << json_data.at("Test") << std::endl;
    std::cout << json_data.at("Foo") << std::endl;

    json_data.at("Foo") = 4.32; // what if new data is smaller?

Json:

{
   "Foo": 4.32, // this number is smaller than before
   "Number": 100,
   "Test": "Test1"
}} // whoops trailing character from previous data!!

, , .

- :

#include "json.hpp"
#include <iostream>
#include <fstream>
#include <string>

using json = nlohmann::json;

void readAndWriteDataToFile(std::string fileName) {

    json json_data;

    // restrict scope of file object (auto-closing raii)
    if(auto fs = std::ifstream(fileName))
    {
        json_data = json::parse(fs);

        std::cout << "Operation successfully performed\n";
        std::cout << json_data.at("Number") << std::endl;
        std::cout << json_data.at("Test") << std::endl;
        std::cout << json_data.at("Foo") << std::endl;
    }
    else
    {
        throw std::runtime_error(std::strerror(errno));
    }

    json_data.at("Foo") = 4.32;
    std::cout << json_data.at("Foo") << std::endl;
    std::string json_content = json_data.dump(3);

    if(auto fs = std::ofstream(fileName))
    {
        fs.write(json_content.data(), json_content.size());
        std::cout << "Done" << std::endl;
    }
    else
    {
        throw std::runtime_error(std::strerror(errno));
    }

}

int main()
{
    try
    {
        std::string fileName = "C:/new/json1.json";
        readAndWriteDataToFile(fileName);
    }
    catch(std::exception const& e)
    {
        std::cerr << e.what() << '\n';
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
+1

Source: https://habr.com/ru/post/1654268/


All Articles