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

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;
	}
	else
	{
		int mkdirResult = _mkdir(directoryName.c_str());
		if (mkdirResult == 0)
		{
			cout << "The directory is created." << endl;
		}
		else
		{
			cout << "The directory creation failed with error: " + mkdirResult << endl;
		}
	}
}
&#91;/sourcecode&#93;

<strong>Windows CLR Console Application</strong>


#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;
   }
   else
   {
	   try
	   {
		  DirectoryInfo^ directoryInfo = Directory::CreateDirectory(directoryName);
	   }
	   catch ( Exception^ e )
	   {
		   Console::WriteLine(e->ToString());
	   }
   }
}

One Comment

Leave a Reply

How to post code in comments?