![](/img/trans.png)
[英]Why boost::iostream::filtering_ostream using boost::iostreams::zlib_compressor needs to be destroyed for the sink to be written?
[英]Error boost filtering_ostream when returned from a function
關於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;
}
}
您可能收到的任何想法將不勝感激!
謝謝,
戴夫
修正拼寫錯誤( *outFile
和*outFileComp
)之后,我無法重現此問題:使用g ++ 4.8.1 / boost-1.53進行編譯,它將運行並生成兩個良好的文件:10,000行(文件大小為78,890)的test.txt
和testcomp.txt.gz
(文件大小為22,064),該文件會用gunzip解壓縮到test.txt
的確切副本中。
也許在您的真實程序中,您嘗試在程序結束之前(或至少在最后一次對shared_ptr的引用消失之前)檢查文件了嗎? 壓縮過濾流的常見問題是,像使用std::endl
一樣沖洗outFileComp
不會強制到目前為止完全壓縮文件的寫出。
好的,所以在Cubbi的幫助下,我找到了問題-以下行(出現兩次):
out->push(boost::iostreams::file_sink(fileName),std::ofstream::binary);
本來應該:
out->push(boost::iostreams::file_sink(fileName,std::ofstream::binary));
該代碼仍在編譯中,因此我可能在filtering_ostream中的某個位置設置了一個標志,這可能導致進一步的問題。
此修補程序允許按預期方式創建文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.