簡體   English   中英

創建要在函數內編寫的文件的最簡單方法?

[英]Simplest way to create a file for writing within a function?

我有一個像這樣的功能:

void my_func(unordered_map<std::string, std::string> arg){

    //Create/open file object on first call and append to file on every call

    //Stuff
}

在此函數中,我希望寫入文件。 我如何才能做到這一點而不必在調用方中創建文件對象並將其作為參數傳遞呢? 每次調用該函數時,我都希望將最新的寫操作附加到文件末尾。

void my_func(unordered_map<std::string, std::string> arg){

    static std::ofstream out("output.txt");
    // out is opened for writing the first time.
    // it is available for use the next time the function gets called.
    // It gets closed when the program exits.

}

傳遞兩個字符串/字符數組。 一個是文件路徑,另一個是要寫入的數據。 使用fstream myFile(fstream::out | fstream::app)創建文件fstream myFile(fstream::out | fstream::app)

需要更多說明嗎? 如果您願意,我可以寫一個完整的例子。

編輯

忘記了,這會做您想要的,但是您每次都會創建文件對象。 但是,您不會每次都創建一個新文件。 這就是fstream::app的用途。 您打開文件並從頭開始。

另一種選擇是使用函子。 這將使您有可能控制文件對象的生存期,甚至傳遞函數對象

#include <string>
#include <fstream>
#include <unordered_map>
struct MyFunc {
    MyFunc(std::string fname) {
        m_fobj.open(fname);
    };
    ~MyFunc() {
        m_fobj.close();
    };
    void operator ()(std::unordered_map<std::string, std::string> arg) {
       // Your function Code goes here
    };
    operator std::ofstream& () {
        return m_fobj;
    };
    std::ofstream m_fobj;
};

int main() {
    MyFunc my_func("HelloW.txt");
    my_func(std::unordered_map<std::string, std::string>());
    std::ofstream &fobj = my_func;
    return 0;
};

暫無
暫無

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

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