C++ c+中的boost::iostreams::gzip#u解压缩程序出现奇怪错误+;

C++ c+中的boost::iostreams::gzip#u解压缩程序出现奇怪错误+;,c++,boost,deflate,compression,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

全部

我正在开发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
这给了我一个错误

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.
但有趣的是,如果我从明文中删除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 perfect

我做错了什么


编辑我指出了该行的错误。

我认为您需要指定输出流为二进制:

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

然后,在写入之后,执行outStream.close()(以确保压缩输出被刷新;您可以调用flush(),但close()更适合所有文件系统)。然后,也用
binary
打开文件进行读取。注:无需指定
std::ios_base::in
out
),因为它是std::ifstream(ofstream)的默认值。

触发异常的代码行是哪一行?另外,在尝试再次打开文件进行读取之前,您应该关闭
outStream
。@MattMcNabb我编辑并指出了给出错误的行。写入bin文件时,没有错误。读取bin文件并解压缩时会出现错误。@JoshuaSon:我的建议仍然有效。试试看。@JohnZwinck:我有同样的崩溃问题,类似的解压代码,你的答案不起作用。
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 
std::ofstream outStream(binFile, std::ios_base::binary);