Search code examples
c++windowsxerces

Exception in two line Xerces program


The following code gives me an exception on the XMLFormatTarget line, but if I change the string from "C:/test.xml" to "test.xml" it works fine.

// test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/framework/LocalFileFormatTarget.hpp>

using namespace xercesc;

int main()
{
    XMLPlatformUtils::Initialize();

    XMLFormatTarget *formatTarget = new LocalFileFormatTarget("C:/test.xml"); 

    return 0;
}

[edit] Xerces exception is:

Error Message: unable to open file 'C:\test.xml'

Windows exception is:

Access is denied


Solution

  • It could be that you don't have sufficient permissions to write to C:\. In such a case, Xerces might report the error throwing an exception.

    An Access Denied exception is typically what we could expect if you try to write to a system directory without administrator credentials.


    Maybe it has also something to do with the directory separators:

    XMLFormatTarget *formatTarget = new LocalFileFormatTarget("C:\\test.xml");
    

    On Windows, directory separators are backslashes "\". Some libraries don't care (and I never used Xerces, so I can't tell). In C and C++, backslash is also an escape character and so you must double it if you want a litteral "\" in your string.

    Also, telling us what was the exception you got would help us even more.


    Not directly related, but from your code, it seems you never delete formatTarget. I assume this is sample code, but if it is not, you should add the following line to your code:

    delete formatTarget;
    

    Or use a scoped pointer instead:

    boost::scoped_ptr<XMLFormatTarget> formatTarget(new LocalFileFormatTarget("C:\\test.xml"));
    

    To avoid memory leaks.