2017-07-19 117 views
0

我正在使用boost::filesystem創建一個空文件夾(在Windows中)。假設我想創建的文件夾的名稱是新文件夾。當我運行下面的程序時,會按照預期創建一個具有所需名稱的新文件夾。當第二次運行程序時,我想新文件夾(2)被創建。雖然這是一個不合理的期望,但這是我想達到的。有人可以指導我嗎?如何在具有相同名稱的文件夾已存在時使用boost來創建新文件夾?

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

預期輸出:

Expected output

回答

2

這應該很容易做到你想要什麼,而無需使用任何具體的平臺...

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

這顯然無法實現單獨使用升壓。您需要檢查文件夾是否存在並手動生成新名稱。在Windows上,您可以使用PathMakeUniqueNamePathYetAnotherMakeUniqueName shell功能來達到此目的。

+1

_You需要檢查文件夾是否存在以及手動生成新names_ ......而究竟是什麼阻止你這樣做使用boost? – zett42

+0

@ zett42我假設通過*使用boost *人們的意思是*調用這個boost函數*。當然,沒有任何東西阻止某人自己實現這種功能。 – VTT

相關問題