2

I am using boost::filesystem to create an empty folder (in Windows). Let say that the name of the folder that I want to create is New Folder. When I run the following program, a new folder with the required name is created, as expected. When the run the program for the second time, I want New Folder (2) to be created. Though it is an unreasonable expectation, that is what I want to achieve. Can someone guide me?

#include <boost/filesystem.hpp>
int main()
{
     boost::filesystem::path dstFolder = "New Folder";
     boost::filesystem::create_directory(dstFolder);
     return 0;
}

Expected output:

Expected output

2 Answers 2

6

It should be easy to accomplish what you want without using anything platform specific...

std::string dstFolder = "New Folder";
std::string path(dstFolder);

/*
 * i starts at 2 as that's what you've hinted at in your question
 * and ends before 10 because, well, that seems reasonable.
 */
for (int i = 2; boost::filesystem::exists(path) && i < 10; ++i) {
  std::stringstream ss;
  ss << dstFolder << "(" << i << ")";
  path = ss.str();
}

/*
 * If all attempted paths exist then bail.
 */
if (boost::filesystem::exists(path))
  throw something_appropriate;

/*
 * Otherwise create the directory.
 */
boost::filesystem::create_directory(path);
0

This clearly can not be achieved using boost alone. You need to check whether folder exists and manually generate new names. On Windows you can use PathMakeUniqueName and PathYetAnotherMakeUniqueName shell functions for this purpose.

2
  • 5
    You need to check whether folder exists and manually generate new names ... and what exactly prevents you from doing that using boost?
    – zett42
    Jul 19, 2017 at 18:00
  • 1
    @zett42 I assume that by using boost people mean calling this boost function. Of course nothing prevents someone from implementing such function himself. Jul 19, 2017 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.