Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a scope-managed file stream in C++?

Tags:

c++

file

io

Background

Before the introduction of unique_ptr (or boost's scoped pointers) there was this kind of boiler plate pointer memory management everywhere.

int* a = new int(5);
// do stuff
delete a;
a = nullptr

Now we can just do

std::unique_ptr<int> a = std::make_unique<int>(5);

That's it! When a falls out of scope it will take care of all of the cleanup. Not only is it a convenience, it actually helps prevent memory leaks in the case of early returns or thrown exceptions.

Question

When writing to a file stream I notice the same boiler plate code

std::ofstream ofs;
ofs.open("out.txt");
// writing stuff
ofs.close();

Is there a similar mechanism to handle file opening and closing via RAII? So when the stream (or some kind of wrapper) falls out of scope, it will automatically fall out of scope and release the file handle? Otherwise we may have the same issue we had with pointers, where if you return early the file may not be closed.

like image 224
Cory Kramer Avatar asked Oct 31 '25 05:10

Cory Kramer


2 Answers

ofstream itself is scope-bound, with constructors that can open a file and a destructor that closes it. So you can just write

{
    std::ofstream ofs("out.txt");
    // writing stuff
}

with the same behaviour as your code, plus RAII goodness.

like image 123
Mike Seymour Avatar answered Nov 01 '25 18:11

Mike Seymour


According to http://en.cppreference.com/w/cpp/io/basic_fstream the file will get closed when destructor is called, so file streams should be RAII already.

like image 21
Creris Avatar answered Nov 01 '25 19:11

Creris