Open 方法仅打开具有完整路径的文件 C++
如果我写入完整路径(完整路径/roots.txt),文件将打开。 如果我只写文件名(roots.txt),文件将无法打开
但是,roots.txt 与 main.cpp 位于同一文件夹中。 我应该在 XCode 上检查任何设置吗?
这是代码:
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;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
默认情况下,Xcode 工作目录类似于
~/Library/Developer/Xcode/DerivedData/project-/Build/Products/Debug。
因此,如果您尝试使用相对于您的项目的相对路径目录或任何其他目录,您应该在 Xcode 中手动配置您的工作目录。您可以通过以下方式执行此操作:产品 ->方案->编辑方案->选项选项卡,勾选使用自定义工作目录复选框并显示您的路径。
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.
如果当您尝试使用绝对路径打开文件时它有效,但仅显示文件名失败,则您的相对路径可能不正确。确保
roots.txt
放置在当前工作目录中。查看unistd.h
中声明的getcwd
函数。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 thegetcwd
function declared inunistd.h
.要在从 XCode 内部运行时更改工作目录:在“项目”菜单中选择“编辑活动可执行文件”。
您可以在“常规”部分底部调整工作目录设置。
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.
假设您从 XCode 中运行文件,工作目录不太可能与 .cpp 文件所在的目录相同。检查您当前的工作目录是否是您认为的那样。 (您应该能够使用
getcwd
调用获取它)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)