2011-08-06 79 views
3

所以我有一些基地boost::filesystem::path Base我想創建文件夾,如果一個不存在,並從字符串創建一個二進制文件。目前我有這樣的功能:如何將文件保存到可能的新目錄中?

void file_service::save_string_into_file(std::string contents, std::string name) 
{ 
    std::ofstream datFile; 
    name = "./basePath/extraPath/" + name; 
    datFile.open(name.c_str(), std::ofstream::binary | std::ofstream::trunc | std::ofstream::out ); 
    datFile.write(contents.c_str(), contents.length()); 
    datFile.close(); 
} 

它需要從目錄中存在。所以我想知道如何更新我的函數boost.filesystem APIs以達到所需的功能?

回答

6

請注意,爲了使用boost :: filesystem庫,您需要鏈接預編譯的boost :: filesystem靜態庫和boost :: system靜態庫。

#include "boost/filesystem.hpp" 

boost::filesystem::path rootPath ("./basePath/extraPath/"); 
boost::system::error_code returnedError; 

boost::filesystem::create_directories(rootPath, returnedError); 

if (returnedError) 
    //did not successfully create directories 
else 
    //directories successfully created 
4

boost::filesystem中有create_directories便利功能。它遞歸地創建目錄,所以你不必自己遍歷可能的新路徑。

這是在<boost/filesystem/convenience.hpp>

相關問題