如何在IOS中使用fstream读取XML文件

时间:2014-02-21 11:43:26

标签: c++ ios xcode fstream

我正在使用XCode,这是XCode中的c ++代码

std::fstream stream("templates.Xml", std::ios::binary | std::ios::in);
if(!stream) return false;

enter image description here

我将Xml文件放在包含“.xcodeproj”的文件夹中,然后将其放在包含“.app”的文件夹中,但是流总是返回false,为什么?

2 个答案:

答案 0 :(得分:3)

看起来您正在尝试从错误的目录中打开文件。 “templates.Xml”保存在软件包中 - 未保存在文档目录中。默认情况下,如果打开“./filename”,则实际指向:

/ Users / arinmorf / Library / Application Support / iPhone Simulator / 7.0.3 / Applications / 246E91F9-FAB2-4A46-B1F1-855B5363F24D / Documents /

其中arinmorf将是您的用户名,每次在模拟器上安装应用程序时,都会随机生成长十六进制字符串。

templates.xml文件可在以下位置找到: / Users / arinmorf / Library / Application Support / iPhone Simulator / 7.0.3 / Applications / 246E91F9-FAB2-4A46-B1F1-855B5363F24D / iFly.app / templates.xml

iFly.app是我的应用程序的名称,你的是“T”。但是你不能在项目中使用绝对路径,因为随机生成的字符串,你需要使用NSBundle或CFBundleRef。

在objective-C中,您将使用:

filePath = [[NSBundle mainBundle] pathForResource:@"templates" ofType:@"xml"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];

在C ++中它看起来像:

CFURLRef fileURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("templates"), CFSTR("xml"), NULL);
CFStringRef filePath = CFURLCopyFileSystemPath(fileURL, kCFURLPOSIXPathStyle);
CFStringEncoding encodingMethod = CFStringGetSystemEncoding();
const char *path = CFStringGetCStringPtr(filePath, encodingMethod);
FILE* f = fopen(path, "r");

(感谢Chris Frederick在https://stackoverflow.com/a/8768366/2070758的C ++版本)

答案 1 :(得分:0)

是的,我以两种方式解决了这个问题,要么取决于主要捆绑包,要么创建自定义捆绑包并使用它。