Search code examples
c++cocos2d-xrapidjson

I want to edit a file with RapidJSON but when I do, the file is not saved


This is my code

std::ifstream     infile("/home/alexander/MyCompany/MyGame/Resources/res/puzzles(copia).json");
std::string line;
std::ofstream ofs("/home/alexander/MyCompany/MyGame/Resources/res/temporal.json", std::ofstream::out);

Document d;

while (std::getline(infile, line))
{
    d.Parse(line.c_str());

    if (d.HasParseError())  CCLOG("GetParseError %s\n", d.GetParseError());

    if (d.IsObject() && d.HasMember("Lados"))
    {
        rapidjson::Value& a = d["Lados"];                           // Using a reference for consecutive access is handy and faster.
        rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
        assert(a.IsArray());                                        // explotar si no es un arreglo

        a.PushBack(4, allocator).PushBack(8, allocator).PushBack(15, allocator).PushBack(16, allocator).PushBack(23, allocator).PushBack(42, allocator);

    }

    // Convertir JSON a string e Insertar en archivo
    StringBuffer strbuf;
    Writer<StringBuffer> writer(strbuf);
    d.Accept(writer);

    ofs << strbuf.GetString() << "\n";
}

ofs.close();
infile.close();

// ACTUALIZA ARCHIVO PRINCIPAL & LIMPIA TEMPORAL
std::ifstream  src("/home/alexander/MyCompany/MyGame/Resources/res/puzzles(copia).json");
std::ofstream  dst("/home/alexander/MyCompany/MyGame/Resources/res/temporal.json");

dst << src.rdbuf();

src.close();
dst.close();
if (remove("/home/alexander/MyCompany/MyGame/Resources/res/temporal.json") != 0) CCLOG("Error deleting file");


CCLOG("save");   

As you can see I'm creating a new file called temporal in which'll put my modified file, then pass it back to the original file. the problem is that when I do that the file does not change,it is created and properly cleared but the file orginal is not modify and don't know why?. I am using cocos2d-x, c ++ and rapidjson. not if I need to give permission for my program to modififque arhivos or something like that

JSON has several lines in this format:

{ "N" : 5, "Rotacion" : 42, "Igual" : 20, "Inverso" : 0, "RotacionE" : 47, "Espejo" : 22, "Puntuacion" : 0, "_id" : "563b7b4756ab632f47fe6d7f" , "Lados" : [], "Camino" : [ 6, 5, 4, 21, 22, 7, 2, 3, 20, 23, 8, 1, 18, 19, 24, 9, 0, 17, 16, 15, 10, 11, 12, 13, 14 ], "__v" : 0 }


Solution

  • as I can see your code is ok, what you have to do is reverse the direction of your files .json right now you have it like so:

    std::ifstream  src("/home/alexander/MyCompany/MyGame/Resources/res/puzzles(copia).json");
    std::ofstream  dst("/home/alexander/MyCompany/MyGame/Resources/res/temporal.json");
    

    but you have to put it like this :

    std::ifstream  src("/home/alexander/MyCompany/MyGame/Resources/res/temporal.json");
    std::ofstream  dst("/home/alexander/MyCompany/MyGame/Resources/res/puzzles(copia).json");