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


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

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements