如何将文件保存到可能是新目录中?

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 API来实现所需的功能?

2个回答

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>中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接