gpt4 book ai didi

c++ - 如何制作文件夹/目录

转载 作者:IT老高 更新时间:2023-10-28 22:38:57 27 4
gpt4 key购买 nike

如何使用 c++ 创建目录/文件夹。我尝试使用 mkdir() 没有成功。我想编写一个程序,其中 cin 是一个变量,然后使用该变量在其中创建子目录和文件。我当前的代码。它说 mkdir() 中的 + 运算符表示错误无操作数

char newFolder[20];

cout << "Enter name of new project without spaces:\n";
cin >> newFolder;
string files[] = {"index.php"};
string dir[] = {"/images","/includes","/includes/js","/contact","about"};

for (int i = 0; i<=5; i++){
mkdir(newFolder + dir[i]);
ofstream write ("index/index.php");
write << "<?php \n \n \n ?>";
write.close();
}

最佳答案

您需要 #include <string> , std::string运算符在该 header 中定义。

表达式 newFolder + dir[i] 的结果是 std::string , 和 mkdir()需要 const char* .改为:

mkdir((newFolder + dir[i]).c_str());

查看mkdir()的返回值确保成功,如果不使用 strerror(errno)获取失败的原因。

这会超出数组的末尾 dir :

for (int i = 0; i<=5; i++){
mkdir(newFolder + dir[i]);

5 dir 中的元素,因此合法索引来自 04 .改为:

for (int i = 0; i<5; i++){
mkdir(newFolder + dir[i]);

使用 std::string对于 newFolder , 而不是 char[20] :

std::string newFolder;

那么您无需担心输入的文件夹超过 19 个字符(空终止符需要 1 个字符)。

关于c++ - 如何制作文件夹/目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9920278/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com