In this section, we will see how to get the current working directory using C or C++. We have defined some flags for the current operating system.
Example Code
#ifdef WINDOWS #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif #include<iostream> using namespace std; std::string get_current_dir() { char buff[FILENAME_MAX]; //create string buffer to hold path GetCurrentDir( buff, FILENAME_MAX ); string current_working_dir(buff); return current_working_dir; } main() { cout << get_current_dir() << endl; }
Output
D:\C++ Programs\section 53