在c ++中使用boost :: iostreams :: gzip_decompressor的奇怪错误

时间:2014-03-08 01:46:06

标签: c++ boost deflate compression

所有

我正在开发使用c ++中的boost进行压缩和解压缩。

我的代码如下:

#include <stdio.h>
#include <vector>
#include <string>

#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>

char *txtFile   = "D:/Temp/plainTest.txt";
char *txtFile2  = "D:/Temp/plainTest_.txt";
char *binFile   = "D:/Temp/plainTest.bin";

// compress
std::ifstream inStream(txtFile, std::ios_base::in);
std::ofstream outStream(binFile, std::ios_base::out);
boost::iostreams::filtering_streambuf< boost::iostreams::input> in;
in.push( boost::iostreams::gzip_compressor());
in.push( inStream );
boost::iostreams::copy(in, outStream);

// decompress
std::ifstream inStream2(binFile, std::ios_base::in);
std::ofstream outStream2(txtFile2, std::ios_base::out);
boost::iostreams::filtering_streambuf< boost::iostreams::input> in2;
in2.push( boost::iostreams::gzip_decompressor());
in2.push( inStream2 );
boost::iostreams::copy(in2, outStream2);   --->   this line gives me the following error

plainText.txt文件包含这些字符。

The following line is in error

std::ofstream ofs
The compiler would've spit out a warning (at least) if your file was called jest; but 

这给了我一个错误。

First-chance exception at 0x75692EEC in C_test.exe: Microsoft C++ exception: boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::iostreams::zlib_error> > at memory location 0x00D8E074.

If there is a handler for this exception, the program may be safely continued.

0x75692EEC的内存就像

0x75692EEC  8b 4c 24 54 33 cc e8 9d a2 ff ff 8b e5 5d c2 10 00 8b 45 10 83 f8 0f 77 18 89 44 24 10 c1 e0 02 50 51 8d 44 24 1c 50 e8 c9 ad ff ff 83 c4 0c eb c5 6a 0f 58 eb e3 90 90 90 90 90 8b ff 55  ?L$T3????..??]?..?E.??.w.?D$.??.PQ?D$.P???..??.??j.X????????.U

但有趣的是,如果我从plainText.txt删除 ofs ,如

The following line is in error

std::ofstream
The compiler would've spit out a warning (at least) if your file was called jest; but 

错误消失了,它将生成plainText2.txt完美。

我做错了什么?

编辑我指出这行给了我错误。

1 个答案:

答案 0 :(得分:0)

我认为你需要指定输出流是二进制的:

std::ofstream outStream(binFile, std::ios_base::binary);

然后,在写完之后,执行outStream.close()(以确保刷新压缩输出;您可以调用flush(),但close()更可以在所有文件系统上工作)。然后,打开文件以便使用binary进行阅读。请注意,无需指定std::ios_base::inout),因为它是std :: ifstream(ofstream)的默认值。