Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++17 create directories automatically given a file path

#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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading