xcode 如何将工作目录更改为程序所在的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13225500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to change the working directory to the location of the program
提问by Yuchen Zhong
I want to use c++ to open a file on Mac OS.
我想使用 C++ 在 Mac OS 上打开文件。
If I run the program under Xcode, the working directory is the same with the program, which is fine. However, if I try to run the program in terminal, the working directory is alway "Users/username". Do you know how to change the working directory to the location of the program?
如果我在Xcode下运行程序,工作目录和程序是一样的,没问题。但是,如果我尝试在终端中运行该程序,则工作目录始终为“用户/用户名”。您知道如何将工作目录更改为程序所在的位置吗?
Here is the sample code:
这是示例代码:
#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, const char * argv[])
{
char * dir = getcwd(NULL, 0);
cout << "Current dir: " << dir << endl;
ifstream fin("hi.txt");
if (fin.is_open()) cout << "File is Open" << endl;
else cout << "File is not open" << endl;
fin.close();
return 0;
}
回答by Matt Connolly
Use the value $(PROJECT_DIR)
in the working directory in your scheme debug settings:
$(PROJECT_DIR)
在您的方案调试设置中使用工作目录中的值:
回答by Mark Szymczyk
You can set a custom working directory for your project in Xcode. In Xcode 4 choose Edit Scheme from the Scheme menu in the project window toolbar to open the scheme editor. Select the Run step from the left side of the project editor. Click the Options button at the top of the scheme editor. Select the Use custom working directory checkbox. Click the button on the right side of the text field to choose the working directory.
您可以在 Xcode 中为您的项目设置自定义工作目录。在 Xcode 4 中,从项目窗口工具栏中的 Scheme 菜单中选择 Edit Scheme 以打开方案编辑器。从项目编辑器的左侧选择 Run 步骤。单击方案编辑器顶部的选项按钮。选中使用自定义工作目录复选框。单击文本字段右侧的按钮以选择工作目录。
回答by llakais
You could use chdir(), see here: Change the current working directory in C++.
您可以使用 chdir(),请参见此处:Change the current working directory in C++。
Or if you could always just issue a system call (stdlib.h): http://www.cplusplus.com/reference/clibrary/cstdlib/system/. This won't be portable, but it might be good enough for what you need.
或者,如果您总是可以发出系统调用 (stdlib.h):http://www.cplusplus.com/reference/clibrary/cstdlib/system/。这不会是便携式的,但它可能足以满足您的需要。