删除数据文件中的条目C ++

时间:2015-10-02 11:55:33

标签: c++ xml

在XML .dat文件中,格式如下:

//trees
<object id = "19" x = "834" y = "467" f = "0" />
<object id = "19" x = "823" y = "460" f = "0" />
<object id = "19" x = "825" y = "489" f = "0" />
<object id = "19" x = "821" y = "487" f = "2" />
<object id = "19" x = "825" y = "499" f = "2" />
//well
<object id = "28" x = "824" y = "470" f = "0" />
//statue
<object id = "16" x = "812" y = "473" f = "0" />

因此它包含该信息,.3ds对象的ID及其位置和它应该面对的方向。

在我的项目中,我遍历下面.dat文件中的每一行,如果x和y值与输入相同,我希望删除该行。

// delete an object
void MapEditor::deleteObject(int xx, int zz){

    stringw path = Client::getCacheFile("Cache/Cache_file_3/models/object_test.dat");

    io::IXMLReader* reader = Client::device->getFileSystem()->createXMLReader(path);
    const stringw object("object");

    while (reader->read()) {
        switch (reader->getNodeType()) {
            //we found a new element
        case irr::io::EXN_ELEMENT:
            //new <object> tag
            if (object.equals_ignore_case(reader->getNodeName())) {
                u16 id = reader->getAttributeValueAsInt(L"id");
                u16 x = reader->getAttributeValueAsInt(L"x");
                u16 y = reader->getAttributeValueAsInt(L"y");

                // if the mouse click location matches an 
                    //object in the data file then execute the following
                if ((x == xx) && (y = zz)){
                    //cout << "we have a winner! Its ID is: " << id << endl; 
                    // this is where it would delete
                }
            }
            break;
        }
    }
}

我不确定如何删除我想要的行 - 我是否需要将整个文件复制到某个字符串并对其执行字符串替换?或者有更好的方式

1 个答案:

答案 0 :(得分:1)

关于删除文件中间文本的堆栈溢出实际上有很多问题:Remove memory from the middle of a file

文件应该被视为一个数组。不是链表。就像一个阵列,你不能说,我想删除元素13 - 42,但剩下的就剩下了。相反,您必须将之前和之后的所有元素复制到新分配的数组中。

这是一个很长的答案:是的,你需要重写文件。