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

标签 c++ directory mkdir

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

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

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

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

编译器编译没有问题,就是不行。它打印 10 次 “Impossible create folder n”。怎么了?

在使用 c_str() 将字符串转换为 const char*? 时,我可能犯了一个错误。

此外,有没有办法使用其他方式创建文件夹?我查看了 CreateDirectory(); (API),但它使用了像 DWORD 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;
}

最佳答案

如果你的编译器支持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;
}

关于c++ - 如何创建目录 C++(使用 _mkdir),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57358730/

相关文章:

C# 目录搜索模式子目录

c++ - mkdir Windows 与 Linux

linux - bash/linux - touch/mkdir 来自文件中的字符串

amazon-web-services - 消息 : mkdir(): Permission denied AWS ec2

ruby-on-rails - Ruby:遍历目录和文件

c++ - 适用于 Linux 的 C/C++ RPC 教程

C++ win32控制台应用程序使用Windows api添加 "choose file"对话框

c++ - Poco::ServerApplication 的多线程问题

java - 更改了 eclipse 中的目录,项目全部变成红色

c++ - Boost Asio GCC 链接错误