Can't read file from a C++ program on a Mac

LustSeeker picture LustSeeker · Aug 16, 2011 · Viewed 9.1k times · Source

First of all, this is part of my code:

....
string input;
getline(cin, input);

ifstream openFile;
openFile.open(input.c_str(), ios::in);

if(openFile.is_open()){
    cout << "File opened" << endl;
}  
else {
    cout << "Cant open the file " << endl;
}

The result always "Cant open the file". I am very, very sure that the files are exists. I have data1.txt, data2.txt ... data10.txt in the same directory (I used XCode to add new empty file, add the data inside and save it).

I do another test, I create a new directory, copy paste the cpp and data files. I run in terminal, and it works, it can read the data file. Why does xcode cant read my data files? Any idea?

Answer

mmmmmm picture mmmmmm · Aug 16, 2011

You need to give the full path to the files. Xcode will run the application from the build directory which is not where the code is.

If the files are copied as part of building an OSX or iOS application you should look at the bundle structure to find the directory.