问题
File opens if I write the full path (full-path/roots.txt). File fails to open if I write the filename only (roots.txt)
And yet, roots.txt is in the same folder as the main.cpp. Is there any settings I should check on XCode?
Here's the code:
string line;
ifstream infile;
infile.clear();
// infile.open("roots.txt");
infile.open("/Users/programming/C++/roots/roots.txt");
if (infile.fail()) cout << "could not open the file: " << strerror(errno);
getline(infile, line);
cout << line;
回答1:
If it works when you attempt to open a file with an absolute path and fails with just the filename, your relative path is likely incorrect. Ensure roots.txt
is placed in the current working directory. Look into the getcwd
function declared in unistd.h
.
回答2:
By default, Xcode working directory is something like ~/Library/Developer/Xcode/DerivedData/project-/Build/Products/Debug.
So,if you are trying to use a relative path with respect your project directory or any other, you should manually configure your working directory in Xcode.
You can do this by: Product -> Scheme -> Edit Scheme -> options tab, tick the use custom working directory checkbox and show your path.
回答3:
To change the working directory when you're running from inside XCode: select "Edit Active Executable" in your "Project" menu.
You can adjust your working directory settings at the bottom of the "General" section.
回答4:
Assuming you're running file from within XCode, the working directory is unlikely to be the same directory where your .cpp file is located. Check what your current working directory is what you think it is. (you should be able to obtain it using a getcwd
call)
来源:https://stackoverflow.com/questions/4796943/open-method-opens-files-with-full-path-only-c