gpt4 book ai didi

c++ - IOS中如何使用fstream读取XML文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:06:26 25 4
gpt4 key购买 nike

我正在使用 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,为什么?

最佳答案

您似乎正试图从错误的目录打开文件。“templates.Xml”保存在包中——不保存在文档目录中。默认情况下,如果您打开“./filename”,这实际上指向:

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

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

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

(C++ 版本归功于 Chris Frederick https://stackoverflow.com/a/8768366/2070758)

关于c++ - IOS中如何使用fstream读取XML文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21933548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com