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; }
source share