当同名文件夹已存在时,如何使用boost创建新文件夹?

jsp*_*p99 2 c++ windows directory boost boost-filesystem

我正在使用boost::filesystem创建一个空文件夹(在 Windows 中)。假设我要创建的文件夹的名称是New Folder。当我运行以下程序时,会按预期创建一个具有所需名称的新文件夹。第二次运行程序时,我希望创建新文件夹 (2)。虽然这是一个不合理的期望,但这就是我想要实现的。有人可以指导我吗?

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

预期输出:

预期输出

G.M*_*.M. 5

在不使用任何特定于平台的东西的情况下,应该很容易完成你想要的......

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);
Run Code Online (Sandbox Code Playgroud)