Why doesn't pugixml write back to the currently opened file?

772 views Asked by At

The following code is basically everything I'm doing - opening an XML file, processing it and (trying to) write it back. But writing back fails, every time. I tried to find a solution wrote code, Googled, but got no answer.

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

So, is it like pugi doesn't close the file after taking in the input or what? That doesn't seem to be the case as I can delete the file while the program is running. Does anyone know why my program reads the file but doesn't write the modifications back into it?

1

There are 1 answers

1
Not a real meerkat On

Try loading the file from an ifstream. This way you have control over the file, and can be sure when it is closed.

// 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.

As to why this happens... The Documentation isn't explicit about it, so it's hard to tell. It seems that it should close the file after loading, but the only way to be sure is by looking at the source code. BTW, if you're on a linux OS, you should be able to delete opened files.