How to change the working directory to the program place

I want to use C ++ to open a file on Mac OS.

If I run the program under Xcode, the working directory is the same as the program, and this is normal. However, if I try to run the program in the terminal, the working directory is always "Users / username". Do you know how to change the working directory to a program location?

Here is a 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; } 
+4
source share
3 answers

Use the value $(PROJECT_DIR) in the working directory in the circuit debugging settings:

enter image description here

+9
source

You can set a custom working directory for your project in Xcode. In Xcode 4, select "Edit Schema" from the "Schema" menu in the toolbar of the project window to open the schematic editor. Select the “Run” step on the left side of the project editor. Click the Options button at the top of the schematic editor. Select the Use custom working directory check box. Click the button on the right side of the text box to select the working directory.

enter image description here

+3
source

You can use chdir (), see here: Change current working directory to C ++ .

Or, if you can always just call the system call (stdlib.h): http://www.cplusplus.com/reference/clibrary/cstdlib/system/ . It will not be portable, but it may be good enough for what you need.

+1
source

Source: https://habr.com/ru/post/1012818/


All Articles