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

How to create directory c++ (using _mkdir)

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

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

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

为此,我将字符串与数字(for 循环的计数器)连接起来,使用 static_cast 转换为 char,然后使用 [=21= 转换字符串],并将其分配给 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;
}

问题是 (path_s + static_cast<char>(i + '0')) 创建了一个 临时 对象。一个生命周期在 c_str() 被调用后结束(并被破坏)的人。

这会给您留下一个指向不再存在的字符串的指针,以几乎任何方式使用它都会导致未定义的行为

而是保存 std::string 对象,并在需要时调用 c_str()

std::string path = path_s + std::to_string(i);
_mkdir(path.c_str());

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

注意在Linux下可以使用mkdir命令如下:

#include <sys/stat.h>
... 
const int dir_err = mkdir("foo", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (-1 == dir_err){
    printf("Error creating directory!n");
    exit(1);
}

可以通过阅读 man 2 mkdir 获得更多信息。