Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a directory in C++

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?

like image 331
user1143336 Avatar asked Jan 19 '12 18:01

user1143336


People also ask

Can you make a directory in C?

This task can be accomplished by using the mkdir() function. Directories are created with this function. (There is also a shell command mkdir which does the same thing). The mkdir() function creates a new, empty directory with name filename.

What is directory in C programming?

The directory is a place/area/location where a set of the file(s) will be stored. Subdirectory is a directory inside the root directory, in turn, it can have another sub-directory in it. In C programming language you can list all files and sub-directories of a directory easily.

How do you create a file and directory?

Navigate to where you want to create the new folder, and click New Folder. Type the name of your folder, and press Enter. To save a document to the new folder, open the document, and click File > Save As, and then browse to the new folder, and click Save.


2 Answers

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"

like image 179
josephthomas Avatar answered Oct 10 '22 06:10

josephthomas


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

like image 44
Tony Tannous Avatar answered Oct 10 '22 05:10

Tony Tannous