Find out the current working directory in C/C++

CC++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 02-Apr-2019 08:43:34
Advertisements