Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

c++ - how to change the working directory to the location of the program

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...