Placing Data in Specific Folders in C++ - dummies

Placing Data in Specific Folders in C++

By John Paul Mueller, Jeff Cogswell

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 <direct.h> 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 <iostream>
#include <direct.h>
#include <stdlib.h>
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!