简体   繁体   中英

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.

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 );
        }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM