删除数据文件中的条目

Delete an entry in a data file C++

本文关键字:数据 文件 删除      更新时间:2023-10-16

在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;
        }
    }
}

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

实际上有很多关于在文件中间删除文本的堆栈溢出问题:

文件可以看作是一个数组。不是链表。就像一个数组,你不能说,我想删除元素13 - 42,但留下其余的。相反,必须将数组前后的所有元素复制到新分配的数组中。

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