I am porting a c++ application to ios, and my app needs to access some external files.
Two questions about ios app accessing files:
the code can only access files in the "app bundle"?
can we use c++ to access those files? how?
For example, I tried to use
string cpp_function()
{
string line;
ifstream myfile ("example");
if (myfile.is_open()){
getline (myfile,line);
return line;
}
return "failed";
}
the file "example" exists in the same folder as the code, but it always returns "failed". My guess: this file is copied into the Resources folder, so when we run this code on the simulator or device, they are no longer in the same place?
The problem with what you're trying is that you are not including the full file path in this line
ifstream myfile ("example");
I don't know much about C++, but I do know that if you wanted to access a file in iOS using the C standard library, you would have to do this
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@""];
FILE *f = fopen(filePath.UTF8String, "r"); //works
FILE *f = fopen("example", "r"); //does not work
Also note that you can only access files in your app bundle. You could try this by using Objective-C++ and getting the path for the file you are looking for through this method
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@""];
std::string *path = new std::string([filePath UTF8String]);
ifstream myfile (path);
Be aware that you can read from, but you cannot write to the app bundle, but you can write to the documents directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With