最简单的方法来创建一个文件在一个函数内写入?

最简单的方法来创建一个文件在一个函数内写入?

问题描述:

我有一个像这样的函数:

I have a function like so:

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
}

在这个函数里面我想写一个文件。如何实现这一点,而不必在调用者中创建文件对象,并将其作为参数传递?每次调用函数时,我想将最新的写入附加到文件末尾。

and inside this function I wish to write to a file. How can I achieve this without having to create the file object in the caller and pass it in as a parameter? Each time the function is called I would like to append the latest write to the end of the file.

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.

}