Open method opens files with full path only C++

心已入冬 提交于 2020-01-15 09:04:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!