1

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.

user997112
  • 29,025
  • 43
  • 182
  • 361

3 Answers3

2
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.

}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

Pass two strings/char arrays. One is the file path, the other is the data to be written. Create the file using fstream myFile(fstream::out | fstream::app)

Need anymore explanation? I can write a full example if you would like.

Edit

Forgot to mention, this will do what you want, but you will be creating the file object everytime. You will not be creating a new file everytime though. That's what fstream::app is for. You open the file and start at the end.

Hill
  • 463
  • 3
  • 15
1

Another alternative is to use a functor. This will give you the potential to control the lifetime of the file object and even pass around the function object

#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;
};
Abhijit
  • 62,056
  • 18
  • 131
  • 204