Arun
Arun

Reputation: 2373

klocwork issue for std::ofstream open

Klocwork throws

resource acquired to 'ofs.open("file.txt", std::ofstream::out)' may be lost here

for the below piece of code.

#include <iostream>
#include <fstream>

void main()
{
    std::ofstream ofs;
    ofs.open("file.txt", std::ofstream::out);
    if (ofs.is_open())
    {
        std::cout << "file open success\n";
    }
    ofs.close();
}

I dont find any issues with the above code. Can someone explain what need to be done here to fix the issue.

Upvotes: 2

Views: 514

Answers (1)

Joe
Joe

Reputation: 56

Are you still having this issue? I have a workaround that satisfies Klocwork: use RAII:

std::ofstream ofs( "file.txt", std::ios::binary );

If that doesn't work, use a temp.

        std::ofstream temp( "file.txt", std::ios::binary );
        if( !temp.is_open() )
        {
            temp.close();
        }
        else
        {
            m_outStream = std::move( temp );
        }  

Upvotes: 3

Related Questions