How to create a directory in C++
Asked Answered
C

3

12

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?

Cortisol answered 19/1, 2012 at 18:17 Comment(4)
CreateDirectory ("C:\\Users\\morons", NULL);Obstetrician
I've tried but in this way doesn't create anything.Cortisol
Do you have permissions to create directories in C:\Users? You may need to run the program as admin to have the necessary permissions.Obstetrician
That directory literally made me LOL!Halide
M
40

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"

Mastin answered 19/1, 2012 at 18:27 Comment(1)
It's highly unfair that I got all the upvotes, when this is a far better answer than mine. Have an upvote :-)Retirement
R
22

You need another backslash in there:

CreateDirectory ("C:\\Users\\morons", NULL);
Retirement answered 19/1, 2012 at 18:18 Comment(1)
...or you can use forward slashes: CreateDirectory("c:/user/morons"). Windows requires back-slashes on the command line, but the API accepts either back slashes or normal ones.Boomkin
S
5

Making a windows application cross-platform, was using CreateDirectory() c++17 standard now has std::filesystem::create_directories

#include<iostream>
#include <filesystem>

int main()
{
    std::filesystem::create_directories("C:\\newfolder\\morons");
}

Needs changes in makefile to -std=c++17 and updating to a GCC compiler that supports c++17.

In visual studio follow steps here to enable c++17

Stertor answered 3/9, 2019 at 11:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.