Domanda

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;

enter image description here

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?

È stato utile?

Soluzione

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)

Altri suggerimenti

Yes, I solved the problem in two ways either depending on Main Bundle, or create custom bundle and use it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top