Friday, April 8, 2022

[SOLVED] C++17 create directories automatically given a file path

Issue

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream fo("output/folder1/data/today/log.txt");
    fo << "Hello world\n";
    fo.close();

    return 0;
}

I need to output some log data to some files with variable names. However, ofstream does not create directories along the way, if the path to the file doesn't exist, ofstream writes to nowhere!

What can I do to automatically create folders along a file path? The system is Ubuntu only.


Solution

You can use this function:

bool CreateDirectoryRecuresive(const std::string & dirName)
{
    std::error_code err;
    if (!std::experimental::filesystem::create_directories(dirName, err))
    {
        if (std::experimental::filesystem::exists(dirName))
        {
            return true;    // the folder probably already existed
        }

        printf("CreateDirectoryRecuresive: FAILED to create [%s], err:%s\n", dirName.c_str(), err.message().c_str());
        return false;
    }
    return true;
}

(you can remove the experimental part if you have new enough standard library).



Answered By - wohlstad
Answer Checked By - Robin (WPSolving Admin)