13

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

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();
}
Cjueden
  • 1,200
  • 2
  • 13
  • 25
  • 1
    `mkdir()` is the right way to do it, at least on a POSIX system. What happened when you tried it? – Wyzard Mar 29 '12 at 06:43

1 Answers1

12

You need to #include <string>, the std::string operators are defined in that header.

The result of the expression newFolder + dir[i] is a std::string, and mkdir() takes a const char*. Change to:

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.

This accesses beyond the end of the array dir:

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

there are 5 elements in dir, so legal indexes are from 0 to 4. Change to:

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

Usestd::string for newFolder, rather than 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.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Thank you for your help I changed the for condition but it still says the same thing, I can't get past the error to see any output. – Cjueden Mar 29 '12 at 06:56
  • Again thank you but the + in the mkdir is still erroring it says no operator "+" matches these operands – Cjueden Mar 29 '12 at 07:00