我想用RapidJSON编辑文件,但是当我这样做时,文件没有保存

时间:2015-12-06 21:15:31

标签: c++ cocos2d-x rapidjson

这是我的代码

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");   

正如您所看到的,我正在创建一个名为temporal的新文件,其中将放置我修改过的文件,然后将其传递回原始文件。 问题是,当我这样做时,文件没有改变,它被创建并正确清除,但文件原始不修改,不知道为什么? 我正在使用cocos2d-x,c ++和rapidjson。 如果我需要允许我的程序修改arhivos或类似的东西

JSON有以下格式的几行:

{ "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 }

1 个答案:

答案 0 :(得分:0)

因为我可以看到你的代码没问题,你要做的就是改变你文件的方向。现在你就像这样:

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

但你必须这样说:

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