Search code examples
c++fileboostsaveboost-filesystem

How to save file into possibly new directory?


So I have some base boost::filesystem::path Base I want to create folder if one does not exist and create a binary file from string. Currently I have a function like this:

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();
}

It requires from the directories to exist. So I wonder how to update my function to boost.filesystem APIs in order to reach desired functionality?


Solution

  • Note that in order to use the boost::filesystem library, you will need to link against the pre-compiled boost::filesystem static library, and the boost::system static library.

    #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