C++ 如何制作文件夹/目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9920278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a folder/directory
提问by Cjueden
How do I make a directory/folder with c++. I've tried to use the mkdir() without success. I want to write a program that cin's a variable and then uses this variable to create sub-directory's and files with in those. my current code. It says the + operator in the mkdir() says error no operand
如何使用 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();
}
采纳答案by hmjd
You need to #include <string>, the std::stringoperators are defined in that header.
您需要#include <string>,std::string运算符在该标题中定义。
The result of the expression newFolder + dir[i]is a std::string, and mkdir()takes a const char*. Change to:
表达式的结果newFolder + dir[i]是 a std::string,并mkdir()采用 a const char*。改成:
mkdir((newFolder + dir[i]).c_str());
Check the return value of mkdir()to ensure success, if not use strerror(errno)to obtain the reason for failure.
检查返回值mkdir()以确保成功,如果不使用则strerror(errno)获取失败的原因。
This accesses beyond the end of the array dir:
这访问超出数组的末尾dir:
for (int i = 0; i<=5; i++){
mkdir(newFolder + dir[i]);
there are 5elements in dir, so legal indexes are from 0to 4. Change to:
还有5的元素dir,所以法律索引是从0到4。改成:
for (int i = 0; i<5; i++){
mkdir(newFolder + dir[i]);
Usestd::stringfor newFolder, rather than char[20]:
使用std::string的newFolder,而不是char[20]:
std::string newFolder;
Then you have no concern over a folder of more than 19 characters (1 required for null terminator) being entered.
然后,您不必担心输入的文件夹超过 19 个字符(空终止符需要 1 个字符)。

