2

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?

3
  • 1
    Is this about iOS or Mac development ? What's the exact content of input ? If it's a relative path, is your process in the correct working directory ?
    – DarkDust
    Aug 16, 2011 at 11:11
  • Mac, a cpp command line program. THe input can be: data1.txt, data2.txt
    – LustSeeker
    Aug 16, 2011 at 11:16
  • 1
    Nothing at all to do with Xcode. Aug 16, 2011 at 13:13

2 Answers 2

2

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.

8
  • hmmm.. but i need to past it to others OS environment. Maybe linux?? It wont work again right?
    – LustSeeker
    Aug 16, 2011 at 11:19
  • 1
    If this is pure C++ then it will work in all environments but the question is which directories are the executable and files in. The usual way is to pass the filenames in as parameters to the executable and not rely on them being in the same directory
    – mmmmmm
    Aug 16, 2011 at 11:23
  • @ Mark: Yes, it is pure C++. A very basic one. It works if i compile and run it through mac terminal. But in xcode, it just does not work :(
    – LustSeeker
    Aug 16, 2011 at 11:24
  • 1
    As my answer says the current directory differs if run frokxcode or the command line. Print the value of getcwd() in your program to see. The exec will open files at getcwd()/filename
    – mmmmmm
    Aug 16, 2011 at 11:27
  • The executable's directory can be obtained from argv[0], passed to main(). Aug 16, 2011 at 13:27
1

You can tell Xcode to run the executable from the directory containing the data files.

Bring up the info dialog for the target executable, and change the value for 'Set the working directory to:' to either the Project directory or a custom directory'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.