How to get Current Directory in C++

Hello, Learners here we will see how can we get the current working directory in C++. PATH_MAX is a constant whose value is different for different operating systems. It determines the maximum number of characters allowed in a full pathname. It is a good habit to use PATH_MAX instead of guessing a constant number to use. PATH_MAX is found in the header <limit.h>.

For Linux: Get current directory in C++

The getcwd() is an inbuilt function, which is used to access the current directory. Basically we pass an array to this function and this function places an absolute pathname of the current directory in that array. One can use get_current_dir_name() or getwd() instead of getcwd(). All these functions are available in the header <unistd>

Code 1

#include <unistd.h>
#include <stdio.h>
#include <limits.h>

int main() {
   char buffer[PATH_MAX];
   if (getcwd(buffer, sizeof(buffer)) != NULL) {
       printf("Current working directory : %s\n", buffer);
   } else {
       perror("getcwd() error");
       return 1;
   }
   return 0;
}

We donot need to pass any parameter/array to function get_current_dir_name()

Code 2

#include <unistd.h>
#include <stdio.h>

int main()
 {
   printf("Current working dir: %s\n", get_current_dir_name());
   return 0;
 }

It is notable that in the above two codes we are not using file name to get the current directory. For Linux operating system, one can use any of the two codes given above.

For Windows

When null parameter is passed in function GetModuleFileName, it returns path of the file which has been used to create the calling function. This function may not be available in upcoming days so one can go with the next code given below.

Code 1

#include <windows.h>
#include <string>
#include <limits.h>
#include <iostream>
using namespace std;;

string getCurrentDir() {
    char buff[MAX_PATH];
    GetModuleFileName( NULL, buff, MAX_PATH );
    string::size_type position = string( buff ).find_last_of( "\\/" );
    return string( buff ).substr( 0, position);
}

// Driver function
int main() {
    cout << "Current working directory : " << getCurrentDir() << "\n";
}

Functionality of _getcwd is same as getcwd but in case of Windows operating system _getcwd is used. _wgetcwd and _getcwd behave identically. The only difference is that _wgetcwd wide-character version of _getcwd.

Code 2

#include <direct.h>
#include<limits.h>
#include<iostream>
using namespace std;

main() 
{
  char buff[PATH_MAX];
  _getcwd( buff, PATH_MAX );
  string current_working_dir(buff);
    cout << current_working_dir << endl;
  return 0;
}

It is notable that in the last two codes we are not using file name to get the current directory. For Windows operating system, one can use any of the last two codes given above.

Also read: How to Get all the Files in a Directory using C++

Leave a Reply

Your email address will not be published. Required fields are marked *