两行Xerces程序中的exception

下面的代码给了我一个XMLFormatTarget行exception,但如果我将string从"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; } 

Xercesexception是:

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

Windowsexception是:

访问被拒绝

这可能是因为您没有足够的权限来写入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")); 

避免内存泄漏。

尝试转码文件名:

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

根据这个答案 类似的问题 。

如果仅使用test.xml可以指定相对于当前工作目录(通常是从何处开始)的路径。 所以如果你的程序不是直接在你的C盘上,那么这两个运行可能指向不同的文件。 C:\test.xml可能有错误,但C:\Path\to\your\program\test.xml正确的,所以后者不会例外。

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