简体   繁体   中英

In C++, how to check for errors when writing compressed files with gzstream?

I am using gzstream to write outputs from my C++ program. However, sometimes the resulting file seems to be badly written: zcat: output.txt.gz: unexpected end of file , even though no error was returned by my own program.

Therefore, I would like to catch errors while writing the file, that is without having to wait until the program is finished to do a zcat and see the error above.

Here is the relevant part of my code:

ogzstream outStream;
outStream.open ("output.txt.gz");
if (! outStream.is_open()) { cerr << "error while opening" << endl; exit (1); }
for (size_t i = 0; i < vecResults.size(); ++i)
    outStream << i << " " << vecResults[i] << endl;
outStream.close();

What can be improved? Should I check any error bit after writing with << ? Or after closing? If yes, how can I do that?

(FYI It's quite hard to replicate the error as it happens only rarely, but frequently enough to be annoying.)

You should be able to check the result of outStream.good() after you close it, assuming the error checking is properly implemented internally.

Alternatively you could use the exceptions(...) member to request an exception to be thrown in case of errors.

Edit: the error bits are not reset automatically, so it's safe to just check them at the end; if anything fails in-between you can check at the end.

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