How to Get Current Directory in C++
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++:
// C++ Program to get the current working directory
#include <iostream>
#include <direct.h>
using namespace std;
int main() {
// Define a buffer
const size_t size = 1024;
// Allocate a character array to store the directory path
char buffer[size];
// Call _getcwd to get the current working directory and store it in buffer
if (getcwd(buffer, size) != NULL) {
// print the current working directory
cout << "Current working directory: " << buffer << endl;
}
else {
// If _getcwd returns NULL, print an error message
cerr << "Error getting current working directory" << endl;
}
return 0;
}
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++:
// C++ Program to get the current working directory
#include <filesystem>
#include <iostream>
using namespace std;
int main()
{
// finding and printing the current working directory.
cout << "Current path is " << filesystem::current_path()
<< endl;
return 0;
}
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.