November 18, 2009

How to create a directory in C++ in Windows?

Filed under: C/C++ — J. Abram barneck @ 10:23 am

How to create a directory in C++?

Ok, so this is another task that should be simple but isn’t. Come on C++ Standards people. C++ has been out for decades and you haven’t figured out how to get all Operating Systems to conform to a single piece of code to make a directory? Write an standard and release it.

This document is for Windows, I will talk about FreeBSD some time later.

If wxWidgets can do it with the filefn.h, why can’t the standard C++ Library?

Supposedly Boost can do it also but the standards people are taking their sweet time getting Boost in.

So here is how it can be done. The headers names are the project types I chose in Visual Studio 2008.

Windows Empty Project

Create a main.cpp and put the following in it.

#include <iostream>
#include <string>
#include <direct.h>
#include <sys/stat.h>

using namespace std;

int main ()
	string directoryName = "c:\\programdata\\MyApp";

	struct stat st;
	if (stat(directoryName.c_str(), &st) == 0)
		cout << "The directory exists." << endl;
		int mkdirResult = _mkdir(directoryName.c_str());
		if (mkdirResult == 0)
			cout << "The directory is created." << endl;
			cout << "The directory creation failed with error: " + mkdirResult << endl;

Windows CLR Console Application

#include "stdafx.h"

using namespace System;
using namespace System::IO;
int main()

   String^ directoryName = "C:\\ProgramData\\MyApp";
   if ( Directory::Exists( directoryName ) )
	   Console::WriteLine( "The directory exists.");
       return 0;
		  DirectoryInfo^ directoryInfo = Directory::CreateDirectory(directoryName);
	   catch ( Exception^ e ) 

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: