Alex
Alex

Reputation: 47

ios app access files with C++

I am porting a c++ application to ios, and my app needs to access some external files.

Two questions about ios app accessing files:

  1. the code can only access files in the "app bundle"?

  2. 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?

Upvotes: 3

Views: 3248

Answers (1)

Chris Loonam
Chris Loonam

Reputation: 5745

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.

Upvotes: 2

Related Questions