最简单的方法来创建一个文件在一个函数内写入? [英] Simplest way to create a file for writing within a function?

查看:157
本文介绍了最简单的方法来创建一个文件在一个函数内写入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的函数:

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.

}

这篇关于最简单的方法来创建一个文件在一个函数内写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆