Creating a new directory

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.
If you use windows and have VS2012 you can include <filesystem>
Last edited on
I am on Linux and I wanted to do this with the standard library.
There is currently no C or C++ standard library function which creates a directory.

But most Linux distributions provide the POSIX mkdir function.

1
2
3
#include <sys/stat.h>

int mkdir(const char *path, mode_t mode);


There are plenty of man pages about if you need details, e.g.
http://linux.die.net/man/3/mkdir

Of course, you should check the man page for your distro.

The <filesystem> header that naraku9333 refered to is part of TR2, which are proposed additions for the next (post C++11) version of C++.

Andy
Last edited on
@ostar2

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..
thanks to everybody's suggestion because i needed this type of information...
Thanks, I will try these.
ASIDE

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;
}

Andy

PS What does #defining WIN32_LEAN_AND_MEAN exclude exactly?
http://stackoverflow.com/questions/11040133/what-does-defining-win32-lean-and-mean-exclude-exactly
Last edited on
Topic archived. No new replies allowed.