C++ All-in-One For Dummies, 4th Edition
Book image
Explore Book Buy On Amazon

Sometimes you want to place data in a specific common folder, such as the current working directory — the directory used by the application. C++ provides a method to obtain this information: getcwd(). This method appears in the header.

Using the getcwd() method is relatively straightforward. You create a place to put the information, called a buffer, and then ask C++ to provide the information. The GetWorkingDirectory example demonstrates how to perform this task, as shown here:

#include 
#include 
#include 
using namespace std;
int main()
{
    char CurrentPath[_MAX_PATH];
    getcwd(CurrentPath, _MAX_PATH);
    cout << CurrentPath << endl;
    return 0;
}

As output, you should see the name of the directory that contains the application, such as C:CPP_AIOBookVChapter02GetWorkingDirectory. The _MAX_PATH constant is the maximum size that you can make a path.

So, what this code is saying is to create a char array that is the size of _MAX_PATH. Use the resulting buffer to hold the current working directory (which is where the name of the method getcwd() comes from). You can then display this directory onscreen or use it as part of the path for your output stream — amazing!

About This Article

This article is from the book:

About the book author:

John Paul Mueller has written more than 100 books and more than 600 articles on topics ranging from functional programming techniques to application development using C++.

This article can be found in the category: