C++: gzip on-the-fly komprimieren mit boost::iostreams
English
Deutsch
Dieses minimale Beispiel zeigt Ihnen, wie Sie Daten in eine .gz-Datei in C++ schreiben und die Daten on-the-fly mit boost::iostreams komprimieren. Die Verwendung der modernen iostreams-Schicht im Gegensatz zu einem blockbasierten Ansatz wie zlib ermöglicht es Ihnen, die volle Leistung und Benutzerfreundlichkeit von std::ostream zu nutzen.
gzip_boost_iostreams.cpp
#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
using namespace std;
int main(int argc, char** argv) {
if(argc < 2) {
cerr << "Verwendung: " << argv[0] << " <Ausgabe-.gz-Datei>" << endl;
}
//Dateiname aus dem ersten Befehlszeilenargument lesen
ofstream file(argv[1], ios_base::out | ios_base::binary);
boost::iostreams::filtering_streambuf<boost::iostreams::output> outbuf;
outbuf.push(boost::iostreams::gzip_compressor());
outbuf.push(file);
//Streambuf in ostream umwandeln
ostream out(&outbuf);
//Testdaten schreiben
out << "Dies ist ein Testtext!\n";
//Aufräumen
boost::iostreams::close(outbuf); // Vergessen Sie dies nicht!
file.close();
}CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
find_package(Boost 1.36.0 COMPONENTS iostreams)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(iostreams-gz-compress iostreams-gz-compress.cpp)
target_link_libraries(iostreams-gz-compress ${Boost_LIBRARIES})If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow