gpt4 book ai didi

c++ - 如果我尝试将未压缩的 filtering_istream 复制到 stringstream 会崩溃

转载 作者:行者123 更新时间:2023-11-28 03:53:05 26 4
gpt4 key购买 nike

我想解压缩文件并将其内容写入字符串流。

这是我试过的代码:

string readGZipLog () {
try {
using namespace boost::iostreams;
ifstream file(currentFile.c_str(), std::ios_base::in | std::ios_base::binary);
boost::iostreams::filtering_istream in;
in.push(gzip_decompressor());
in.push(file);
std::stringstream strstream;
boost::iostreams::copy(in, strstream);
return strstream.str();
} catch (std::exception& e) {
cout << e.what() << endl;
}
}

void writeGZipLog (char* data) {
try {
using namespace boost::iostreams;
std::ofstream file( currentFile.c_str(), std::ios_base::out | std::ios_base::binary );
boost::iostreams::filtering_ostream out;
out.push( gzip_compressor() );
out.push(file);
std::stringstream strstream;
strstream << data;
boost::iostreams::copy( strstream, data );
} catch (std::exception& e) {
cout << e.what() << endl;
}
}

它编译时没有任何警告(当然还有错误)但是函数 readGZipLog() 在运行时崩溃了:

gzip error
./build: line 3: 22174 Segmentation fault ./test

./build 是自动编译并启动应用程序./test的脚本

我检查了文件:它包含一些东西,但我无法使用 gunzip 解压它。所以我不确定压缩是否正常工作,以及这是否与 Boost 抛出的 gzip 错误有关。

你能给我打上错误的地方吗?

感谢您的帮助!

保罗

最佳答案

经过大量研究和尝试,我终于找到了一种正确处理(解)压缩的方法。

这是对我来说没有任何问题的代码(使用 gzip 和 bzip2):

string readGZipLog () {
using namespace boost::iostreams;
using namespace std;
try {
ifstream file(currentFile.c_str(), ios_base::in | ios_base::binary);
boost::iostreams::filtering_istream in;
in.push(gzip_decompressor());
in.push(file);
stringstream strstream;
boost::iostreams::copy(in, strstream);
return strstream.str();
} catch (const gzip_error& exception) {
cout << "Boost Description of Error: " << exception.what() << endl;
return "err";
}
}

bool writeGZipLog (char* data) {
using namespace boost::iostreams;
using namespace std;
try {
std::ofstream file( currentFile.c_str(), std::ios_base::app );
boost::iostreams::filtering_ostream out;
out.push( gzip_compressor() );
out.push(file);
stringstream strstream;
strstream << data;
boost::iostreams::copy(strstream, out);
return true;
} catch (const gzip_error& exception) {
cout << "Boost Description of Error: " << exception.what() << endl;
return false;
}
}

我能说的是,我犯了一些不必要的错误,我只是在几个小时后再次查看代码时才发现。 boost::iostreams::copy( std::stringstream , char* ); 例如,如果 1 + 1 为 3,甚至会失败。

我希望这段代码能像帮助我一样帮助其他人。

保罗 :)

关于c++ - 如果我尝试将未压缩的 filtering_istream 复制到 stringstream 会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4717892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com