簡體   English   中英

如何使用 boost 在此路徑中創建文件:“~/testUsr”

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

我想在路徑“~/testUsr”中創建一個文件,而我不知道究竟是哪個“testUsr”。 如果我只使用路徑“~/testUsr”,它將在當前路徑中生成一個目錄“~”而不是“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();
    }
    

在 boost 中使用獲取絕對路徑中的輔助函數

住在科利魯

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

請注意使用path而不是string以使代碼更可靠。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM