简体   繁体   中英

How to read a XML file using fstream in IOS

I am using XCode, and here is a c++ code in XCode

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

在此处输入图片说明

I put the Xml file in the folder that contain the ".xcodeproj", and I put it in the folder that contains ".app" but the stream always return false, why?

It looks like you are trying to open the file from the wrong directory. "templates.Xml" is saved in the bundle- is not saved in the documents directory. By default, if you open "./filename", this actually points to:

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

Where arinmorf would be your username and the long hex string is randomly generated every time you install the app on the simulator.

The templates.xml file would be found in: /Users/arinmorf/Library/Application Support/iPhone Simulator/7.0.3/Applications/246E91F9-FAB2-4A46-B1F1-855B5363F24D/iFly.app/templates.xml

iFly.app is the name of my app, yours would be "T". BUT you can't use the absolute path in your project, because of the randomly generated string, you need to use the NSBundle or CFBundleRef.

In objective-C, you would use:

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

In C++ it looks like:

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

(Credit to Chris Frederick at https://stackoverflow.com/a/8768366/2070758 for C++ version)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM