VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-get-current-directory-in-cpp/

⇱ How to Get Current Directory in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Get Current Directory in C++

Last Updated : 17 Jun, 2024

The current working directory, also known as the present working directory, is the location on the file system where the executing program is located and operates from. When working with files and directories in C++, it is important to determine the current working directory to find the resource files. In this article, we will learn how to get the current directory in C++.

Get Current Working Directory in C++

To get the current working directory in C++, we can use the getcwd() function provided by the <direct.h>header. Below is the syntax to use the getcwd function:

Syntax of getcwd()

char *_getcwd(char *buffer, size_t size);

where:

  • buffer: is a character array that will be used to store the absolute path of the current working directory.
  • size: denotes the maximum length of the buffer array.

C++ Program to get Current Working Directory in Windows Based Systems

The following program illustrates how we can get the current working directory in windows using getcwd function in C++:


Output

Current working directory: C:\Users\Desktop

Time Complexity: O(1)
Auxiliary Space: O(N), here N denotes the maximum size of the buffer array.

Get Current Directory with std::filesystem Method

We can also find the current directory using the new std::filesystem::current_path() method which was introduced in C++17.

C++ Program to get Current Working Directory using Filesystem

The following program illustrates how we can get the current working directory using std::filesystem::current_path() function in C++:


Output

Current working directory: C:\Users\Desktop

Time Complexity: O(1)
Auxiliary Space: O(N), here N denotes the maximum size of the buffer array.

Comment