How do you create a new directory in C++? I would like to do this using the standard library and no external, third party or non standard libraries/headers. I need to do this without calling system() or system("mkdir"). I looked all over the web and could not find any solutions. Thanks.
While creating a Sudoku game in MS Visual 2012 Express, I needed to be able to create a directory to put the game boards in. With help from users on this site, this is what I was able to come up with.
1 2 3 4 5 6 7 8 9 10 11
#include <dirent.h> // May have to find it on the web. I had to. Using it in MS Visual 2012 C++ Express
#include <direct.h> // for getcwd
#include <stdlib.h> // for MAX_PATH
// after the main() declaration
const size_t nMaxPath = 512;
TCHAR szPath[nMaxPath];
GetCurrentDirectory(nMaxPath, szPath);
wcsncpy_s(szPath, _T("Saves"), nMaxPath); // Creates the DIR 'Saves', in the current directory
CreateDirectory(szPath, NULL);
Hope it's a help for you to get your program working..
Personally I would not bother with trying to track down dirent.h. The standard practice/convention is to include windows.h, which will provide GetCurrentDirectory, CreateDirectory, and MAX_PATH. Additional Win32 headers are generally only included for non-core functionality.
If you know you only want the core functionality for your program, you can define WIN32_LEAN_AND_MEAN before including windows.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#define WIN32_LEAN_AND_MEAN
// reduces the size of the Win32 header files by
// excluding some of the less frequently used APIs
#include <windows.h>
#include <tchar.h>
int main(){
TCHAR szPath[MAX_PATH] = _T("");
GetCurrentDirectory(MAX_PATH, szPath);
// remember backslash: GetCurrentDirectory does not terminate
// directory path with one for you
_tcsncpy_s(szPath, _T("\\Saves"), MAX_PATH); // Creates the DIR 'Saves', in the current directory
CreateDirectory(szPath, NULL);
return 0;
}