开发者

Exception in two line Xerces program

开发者 https://www.devze.com 2023-01-04 02:46 出处:网络
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.

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


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.


Try transcoding the filename:

// Convert the path into Xerces compatible XMLCh*. 
XMLCh *tempFilePath = XMLString::transcode(filePath.c_str()); 

// Specify the target for the XML output. 
XMLFormatTarget *formatTarget = new LocalFileFormatTarget(tempFilePath);

as per this answer to a similar question.


If you use only test.xml you specify a path relative to the current working directory (usually where the program was started from). So if your program is not directly on your C: drive, the two runs could point to different files. The C:\test.xml could have an error, but C:\Path\to\your\program\test.xml correct, so the latter gives you no exception.

Anyway, as ereOn said, it would help if we knew which exception is thrown.

0

精彩评论

暂无评论...
验证码 换一张
取 消