Home

Placing Data in Specific Folders in C++

|
Updated:  
2016-03-26 08:29:48
|
From The Book:  
C++ Essentials For Dummies
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 <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!

About This Article

This article is from the book: 

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Jeff Cogswell has been an application developer and trainer for 18 years, working with clients from startups to Fortune 500 companies. He has developed courses on C++ and other technologies.