Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the working directory to the location of the program

Tags:

c++

xcode

macos

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 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?

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;
}
like image 280
Yuchen Avatar asked Nov 05 '12 03:11

Yuchen


1 Answers

Use the value $(PROJECT_DIR) in the working directory in your scheme debug settings:

enter image description here

like image 102
Matt Connolly Avatar answered Nov 01 '22 07:11

Matt Connolly