Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create directory c++ (using _mkdir)

Today I did a lot of research online about how to create a directory on C++ and found a lot of way to do that, some easier than others.

I tried the _mkdir function using _mkdir("C:/Users/..."); to create a folder. Note that the argument of function will be converted into a const char*.

So far, so good, but when I want to change the path, it does not work (see the code below). I have a default string path "E:/test/new", and I want to create 10 sub-folders: new1, new2, newN, ..., new10.

To do that, I concatenate the string with a number (the counter of the for-loop), converted into char using static_cast, then I transform the string using c_str(), and assign it to a const char* variable.

The compiler has no problem compiling it, but it doesn't work. It prints 10 times "Impossible create folder n". What's wrong?

I probably made a mistake when transforming the string using c_str() to a get a const char*?.

Also, is there a way to create a folder using something else? I looked at CreateDirectory(); (API) but it uses keyword like DWORD HANDLE, etc., that are a little bit difficult to understand for a no-advanced level (I don't know what these mean).

#include <iostream>
#include <Windows.h>
#include<direct.h>

using namespace std;

int main()
{
int stat;
string path_s = "E:/test/new";

for (int i = 1; i <= 10; i++)
{
    const char* path_c = (path_s + static_cast<char>(i + '0')).c_str();
    stat = _mkdir(path_c);

    if (!stat)
        cout << "Folder created " << i << endl;
    else
        cout << "Impossible create folder " << i << endl;
    Sleep(10);
}
return 0;
}
like image 483
Riccardo Avatar asked Sep 18 '25 07:09

Riccardo


1 Answers

If your compiler supports c++17, you can use filesystem library to do what you want.

#include <filesystem>
#include <string>
#include <iostream>

namespace fs = std::filesystem;

int main(){
    const std::string path = "E:/test/new";
    for(int i = 1; i <= 10; ++i){
        try{
            if(fs::create_directory(path + std::to_string(i)))
                std::cout << "Created a directory\n";
            else
                std::cerr << "Failed to create a directory\n";\
        }catch(const std::exception& e){
            std::cerr << e.what() << '\n';
        }
    }
    return 0;
}
like image 59
Kaldrr Avatar answered Sep 20 '25 22:09

Kaldrr