只是一个关于 boost::iostream::filtering_ostream() 的快速问题。
我有一个函数(在内部)为 boost::iostream::filtering_ostream 创建一个 shared_ptr,并返回一个指向 std::ostream 的共享指针。
每当我在函数中不使用压缩器时,一切似乎都工作正常,但是一旦我添加了压缩器,输出文件就会损坏。如果我在“getOutputStreamComp”函数中编写文本,那么一切正常。
下面的示例只是将一些数字写入文件,就像 POC 一样。
#include <iostream>
#include <string>
#include <fstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/shared_ptr.hpp>
boost::shared_ptr<std::ostream> getOutputStream(const std::string& fileName)
{
boost::shared_ptr<boost::iostreams::filtering_ostream> out(boost::shared_ptr<boost::iostreams::filtering_ostream>(new boost::iostreams::filtering_ostream()));
out->push(boost::iostreams::file_sink(fileName),std::ofstream::binary);
return out;
}
boost::shared_ptr<std::ostream> getOutputStreamComp(const std::string& fileName)
{
boost::shared_ptr<boost::iostreams::filtering_ostream> out(boost::shared_ptr<boost::iostreams::filtering_ostream>(new boost::iostreams::filtering_ostream()));
out->push(boost::iostreams::gzip_compressor());
out->push(boost::iostreams::file_sink(fileName),std::ofstream::binary);
return out;
}
int main(int argc, char** argv)
{
boost::shared_ptr<std::ostream> outFile = getOutputStream("test.txt");
boost::shared_ptr<std::ostream> outFileComp = getOutputStreamComp("testcomp.txt.gz");
// This file is fine.
for (size_t i(0); i < 10000; ++i)
{
*outFile << "i: " << i << std::endl;
}
// This file is corrupt.
for (size_t i(0); i < 10000; ++i)
{
*outFileComp << "i: " << i << std::endl;
}
}
您可能有的任何想法将不胜感激!
谢谢,
戴夫