两行Xerces程序中的例外情况

时间:2010-06-22 08:33:08

标签: c++ windows xerces

以下代码在XMLFormatTarget行上给出了例外情况,但如果我将字符串从"C:/test.xml"更改为"test.xml",则可以正常使用。

// 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;
}

[编辑] Xerces异常是:

  

错误消息:无法打开文件   'C:\的test.xml'

Windows异常是:

  

访问被拒绝

3 个答案:

答案 0 :(得分:1)

可能是您没有足够的权限来写入C:\。在这种情况下,Xerces可能会报告抛出异常的错误。

如果您尝试在没有管理员凭据的情况下写入系统目录,则Access Denied异常通常是我们所期望的。


也许它还与目录分隔符有关:

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

在Windows上,目录分隔符是反斜杠“\”。有些图书馆不关心(我从未使用过Xerces,所以我无法分辨)。在CC++中,反斜杠也是转义字符,因此如果您想在字符串中使用“\”,那么必须加倍

另外,告诉我们你得到的例外情况会对我们有所帮助。


与您的代码没有直接关系,似乎您永远不会delete formatTarget。我假设这是示例代码,但如果不是,则应在代码中添加以下行:

delete formatTarget;

或者改为使用范围指针

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

避免内存泄漏。

答案 1 :(得分:1)

尝试转码文件名:

// 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);

根据this answersimilar question

答案 2 :(得分:0)

如果仅使用test.xml,则指定相对于当前工作目录的路径(通常是从程序启动的位置)。因此,如果您的程序不直接在您的C:驱动器上,则两次运行可能指向不同的文件。 C:\test.xml可能有错误,但C:\Path\to\your\program\test.xml正确,因此后者不会例外。

无论如何,正如ereOn所说,如果我们知道抛出了哪个异常会有所帮助。