user11594134
user11594134

Reputation: 129

In C++, close a static file stream inside a class member function

I have a C++ program (developed in Visual C++ 2017) that need to output a lot of lines to files. Below are simplified version just to illustrate the problem.

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <algorithm>
#include <numeric>
#include <fstream>

using namespace std;

class Test{
public:
    void output(int a){
        static ofstream out("a.txt", fstream::in | fstream::out | fstream::app);
        out<<a<<"\n";
    }
};

int main()
{
    Test t;
    for(int i = 0; i < 10; i++){
        t.output(i);
    }

    t.~Test();

    remove("a.txt");
}

The remove("a.txt") never works. I understand that the text file is never properly closed. I explicitly call the t.~Test() in hope it will close the static ofstream but it seems id does not work.

The reason to make the ofstream static is it significantly improve the performance of my production code since I assume it just open the file one time and use it instead of open and close the file for each call

I know the design is bad, but this is from legacy code and I am reluctant to change the function signature.

Is there a simple way to make this work without changing the "out" function signature? Thanks

Upvotes: 0

Views: 585

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409356

The life-time of a local static variable is the life-time of the program itself. It will not be destructed until the program exits.

One possible way to go around your problem could be to use a member variable in the class instead. Open the stream in the constructor, and close it in the destructor. If multiple objects of the class needs to share the stream them make it a static member variable which is opened by its definition (remember that static member variables might need separate declaration and definition).

Upvotes: 1

Related Questions