Search code examples
xmlsavetinyxml2

tinyxml2 create file using printer


I am trying to make a xml file using C++ and tinyxml2, to save a games state. Right now I just end up with an empty file, and I don't know why. Any help would be appreciated.

FILE * pFile;
pFile = fopen ("test.xml","w");
XMLPrinter printer(pFile);
printer.OpenElement("Rooms");
printer.OpenElement("room");
printer.PushAttribute("id","RID_DUNGEON_1");
printer.PushAttribute("description","unpleasant dungeon");
printer.PushAttribute("name","dungeon");
printer.OpenElement("items");
printer.OpenElement("item");
printer.PushAttribute("id","torch");
printer.CloseElement();
printer.CloseElement();
printer.CloseElement();
printer.CloseElement();

The end result should be something like this:

<Rooms>
    <room id="RID_DUNGEON_1" description="unpleasant dungeon" name="dungeon">
        <items>
            <item id="torch"/>
        </items>
    </room>
</Rooms>

Solution

  • Writing to FILE* doesn't write on disk, it writes to user-space buffer.

    In order to flush user-space buffer you should call fflush (or fclose that call fflush).

    If you want to be sure that data are written to storage device you should call fsync before fclose.