【问题标题】:How to save file into possibly new directory?如何将文件保存到可能的新目录中?
【发布时间】:2011-10-21 13:09:35
【问题描述】:

所以我有一些基础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 以实现所需的功能?

【问题讨论】:

    标签: c++ file boost save boost-filesystem


    【解决方案1】:

    请注意,为了使用 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
    

    【讨论】:

      【解决方案2】:

      boost::filesystem 中有一个 create_directories 便利功能。它递归地创建目录,因此您不必自己遍历可能的新路径。

      它在<boost/filesystem/convenience.hpp>

      【讨论】:

        猜你喜欢
        • 2020-11-23
        • 1970-01-01
        • 2020-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-22
        • 2020-04-21
        相关资源
        最近更新 更多