How to create a directory in C++

user1143336 picture user1143336 · Jan 19, 2012 · Viewed 51.1k times · Source

i just found a little piece of code that let me create a directory with windows API without using system(). The only problem is that i can't create directory in subdirectory. For example

#include<windows.h>

int main(){
   CreateDirectory ("C:\\random", NULL);
   return 0;
}

Create a folder named random in C.

But if i do

#include<windows.h>

int main(){
   CreateDirectory ("C:\\Users\morons", NULL);
   return 0;
}

It creates in C che folder named Usersmorons and not the folder morons under Users. Any suggest?

Answer

josephthomas picture josephthomas · Jan 19, 2012

You will need admin access to create or delete a folder in C:\Users. Make sure that you are running the .exe as admin, to ensure you have these privileges. If you do not, then CreateDirectory will fail.

To get the error that is returned, use GetLastError. For a reference on the errors that may return, please take a look at the "Return value" section at

http://msdn.microsoft.com/en-us/library/windows/desktop/aa363855%28v=vs.85%29.aspx

Also, the code you are looking for is

CreateDirectory ("C:\\Users\\morons", NULL);

As there needs to be a "\\" before "morons"