今天在网上查了很多关于如何在C++上创建目录 并找到了很多方法来做到这一点,有些比其他的更容易。
我尝试使用 _mkdir
函数 _mkdir("C:/Users/...");
创建一个文件夹。请注意,函数的参数将被转换为 const char*
。
到目前为止一切顺利,但是当我想更改路径时,它不起作用(请参见下面的代码)。我有一个默认的字符串路径 "E:/test/new"
,我想创建 10 个子文件夹:new1
、new2
、 newN
, ..., 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/