0

下面的代码基本上就是我正在做的所有事情——打开一个 XML 文件,处理它并(试图)写回它。但回写失败,每次。我试图找到一个解决方案编写代码,谷歌搜索,但没有得到答案。

xml_parse_result result = doc.load_file("data.xml");
//I checked the value of result, it is equal to status_ok, so the file opened fine.
//...
//some XML processing
//...
bool b = doc.save_file("data.xml"); //b is always false

那么,是 pugi 在接受输入后没有关闭文件还是什么?情况似乎并非如此,因为我可以在程序运行时删除文件。有谁知道为什么我的程序读取文件但不将修改写回其中?

4

1 回答 1

2

尝试从 ifstream 加载文件。这样您就可以控制文件,并且可以确定它何时关闭。

// Initialization code
{
  std::ifstream stream("data.xml");
  pugi::xml_parse_result result = doc.load(stream);
  // Check validity
} // Input stream implicitly destructed and file closed.
// Processing
{
  std::ofstream stream("data.xml");
  doc.save(stream);
} // Output stream implicitly destructed and file closed.

至于为什么会发生这种情况......文档没有明确说明,所以很难说。似乎它应该在加载后关闭文件,但唯一可以确定的方法是查看源代码。顺便说一句,如果您使用的是 linux 操作系统,您应该能够删除打开的文件。

于 2015-06-16T12:54:56.833 回答