Disk gets full during file write. How can I get no

2019-07-14 01:16发布

I have a quite big object to serialize to disk, like this:

if (!EngineFile.empty())
{
    std::ofstream OutEngineStream(EngineFile);
    if (!OutEngineStream)
    {
        std::cerr << "Failed to write to file \"" << EngineFile << "\"! Aborting ..." << std::endl;
        return -1;
    }
    engine->serialize(OutEngineStream);
    OutEngineStream.close();

    std::cout << "\"" << EngineFile << "\" successfully wrote to disk." << std::endl;
}

The problem is, somtimes serialize requires larger disk space than available. e.g. there is only 30M storage available but serialize requires 200M. In this case I can normally open the stream. During serialize everything goes well, and close returns nothing. The program runs well, but there is only a 30M file on the disk.

How can I get to know about this case?

标签: c++ fstream
3条回答
爷的心禁止访问
2楼-- · 2019-07-14 02:02

What about this:

std::fstream file;
file.exceptions( std::fstream::failbit | std::fstream::badbit );
try {
    // do work
}
catch (std::fstream::failure e) {
    std::cerr << "Exception opening/reading/writing/closing file\n";
}
查看更多
Root(大扎)
3楼-- · 2019-07-14 02:08

First of all, serialize should constantly verify whether its write operations succeed and throw should they fail.

In the code you've presented you should check OutEngineStream.fail() (it covers more cases than bad) before calling close (because close may also set this state). This however will still leave serialize implemented incorrectly.

查看更多
Summer. ? 凉城
4楼-- · 2019-07-14 02:09

The presented code checks for failure of opening the file.

In addition it should for failure of the write operation.

That's how to detect if the write operation failed.

查看更多
登录 后发表回答