如何创建目录 C++(使用 _mkdir)

Ric*_*rdo 2 c++ directory mkdir

今天我在网上做了很多关于如何在 C++ 上创建目录的研究,并找到了很多方法来做到这一点,有些方法比其他方法更容易。

我尝试_mkdir使用_mkdir("C:/Users/...");创建文件夹的功能。请注意,函数的参数将转换为const char*.

到目前为止,一切都很好,但是当我想更改路径时,它不起作用(请参阅下面的代码)。我有一个默认的字符串 path "E:/test/new",我想创建 10 个子文件夹:new1, new2, newN, ..., new10

为此,我将字符串与一个数字(for循环的计数器)连接起来,使用 转换为字符static_cast,然后使用转换字符串c_str(),并将其分配给一个const char*变量。

编译器编译它没有问题,但它不起作用。它打印 10 次"Impossible create folder n"。怎么了?

在将字符串 usingc_str()转换为 get a时,我可能犯了一个错误const char*

另外,有没有办法使用其他东西创建文件夹?我查看了CreateDirectory();(API) 但它使用了关键字 likeDWORD HANDLE等,对于非高级级别来说有点难以理解(我不知道这些是什么意思)。

#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;
}
Run Code Online (Sandbox Code Playgroud)

Kal*_*drr 5

如果你的编译器支持 c++17,你可以使用文件系统库来做你想做的事。

#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;
}
Run Code Online (Sandbox Code Playgroud)