Samuel
Samuel

Reputation: 540

Xcode c++ cant access file through code

I have added an image "padimage.png" to my resources folder and set add to target and make copy if needed checked. Then in my c++ code I have the following code to check if it can reach the file

std::ifstream my_file("padimage.png");
if (my_file.good())
{
    std::cout << "could read file \n";
} else {
    std::cout << "could not read file \n";
}

This fails meaning I can't reach the file. I have checked in the debug build folder and the image is there under the resources folder, I have also tried alternative paths to the file like "resources/padimage.png" || Resources/padimage.png || ../Resources/padimage.png etc. etc.

I am fairly new to c++ still so I don't quite understand how it is suppose to find files or what path it searches relative to. Also I am sure this is quite an easy problem but I somehow can't solve it.

All help is much appreciated.

Upvotes: 1

Views: 1647

Answers (2)

Samuel
Samuel

Reputation: 540

Thanks to a suggestion from WhozCraig I have managed to get it working by using the root of the project and then creating a standalone file next to the application like so:

./padimage.png

however this is not ideal. This means I would have resources outside of the project.

But after some trial and error I managed to navigate into the programs package contents by using .app to the package name;

./ProjectName.app/Contents/Resources/padimage.png 

Upvotes: 1

WhozCraig
WhozCraig

Reputation: 66234

Just for your own sanity, do the following before anything else.

char wd[1024];
std::cout << getcwd(wd, sizeof(wd)) << std::endl;

You may be surprised at where you are, and thus why you can't open your file. When running from the IDE you can specify the location of your working directory under the Product/Edit Schemes... area of Xcode (among other places).

Upvotes: 2

Related Questions