how could I create a file in this path : "~/testUsr" by using boost

Viewed 42

I want to create a file in the path "~/testUsr" while I don't know which "testUsr" exactly is. if I just use path "~/testUsr", it will generate a directory "~" in current path instead of "home/testUsr";

// create directories
    std::string directoryPath = "~/testUsr";
    if(!boost::filesystem::exists(directoryPath)){
        boost::filesystem::create_directories(boost::filesystem::path(directoryPath));
    }

    std::string filePath = directoryPath + "/" + filename +".ini";

    if(!boost::filesystem::exists(filePath)){
        boost::filesystem::ofstream File(filePath) ;
        config.WriteConfigFile(filePath);
        File.close();
    }
    
1 Answers

Using a helper function from Getting absolute path in boost

Live On Coliru

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <iostream>

using boost::filesystem::path;

struct {
    void WriteConfigFile(std::ostream& os) const {
        os << "[section]\nkey=value\n";
    }
} static config;

path expand(path p) {
    char const* const home = getenv("HOME");
    if (home == nullptr)
        return p; // TODO handle as error?

    auto s = p.generic_string<std::string>();
    if (!s.empty() && s.find("~/") == 0u) {
        return home + s.substr(1);
    }
    return p;
}

int main() {
    path filename = "abc";

    // create directories
    path directoryPath = expand("~/testUsr");
    if (!exists(directoryPath)) {
        create_directories(directoryPath);
    }

    path filePath = directoryPath / filename.replace_extension(".ini");

    if (!exists(filePath)) {
        boost::filesystem::ofstream os(filePath);
        config.WriteConfigFile(os);
    } // os.close(); implied by destructor
}

Note the use of path instead of string to make the code more reliable.

Related