Sireiz
Sireiz

Reputation: 393

Creating Multiple folders with mkdir() Function using loop c++

I want to create folders in a directory by naming them in a sequence like myfolder1, myfolder2. i tried doing it with mkdir() function using a for loop but it doesn't take 'integer variables' and only takes 'const char values'. what to do now? is there any other function which do that or can mkdir() do that?

Upvotes: 2

Views: 2359

Answers (2)

KyleL
KyleL

Reputation: 1445

I'm not aware of any library calls that take an integer like you are asking. What you need to do is embed the number into the string before passing it to mkdir(). Since you tagged this question with 'c++' I've demonstrated a C++ oriented way of accomplishing this below.

#include <sstream>  // for std::ostringstream
#include <string>   // for std::string

const std::string baseFolderName = "myfolder";
for (int i = 1; i < 20; ++i)
{
    std::ostringstream folderName;
    folderName << baseFolderName << i;
    mode_t mode = 0; //TBD: whatever is appropriate
    mkdir(folderName.str().c_str(), mode);
}

Upvotes: 4

ST3
ST3

Reputation: 8946

If you really want this, you can use itoa(...)

Lets say

i = 20;
char buffer [33];
itoa (i,buffer,10);    //10 means decimal

Now buffer = "20\0"

After this conversion you can add buffer to your default string.

So, all in all, you can use:

std::string str = "string";
char buffer[33] ;
itoa(20, buffer, 10);
str.append(buffer);
mkdir(str.c_str());

Upvotes: 0

Related Questions