2

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?

2 Answers 2

4

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much It did the work! :) and i put some conditional statements too to insert the dates i wanted in the folder names.
0

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());

2 Comments

But then it would be a string, i want to use it in for loop like if your method is correct i would e able to write for (buffer = 0; buffer<21; buffer++) { mkdir("buffer"); } correct?
I'm not sure, what you really want to, but it is possible to write for loop to create some directories.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.