Skip to content

Instantly share code, notes, and snippets.

@jgarzik
Created May 17, 2012 04:03
Show Gist options
  • Save jgarzik/2716209 to your computer and use it in GitHub Desktop.
Save jgarzik/2716209 to your computer and use it in GitHub Desktop.
Append a line of text to a gzip-compressed text file.
/*
Compile on Fedora 16 Linux:
g++ -O2 -Wall -g -o boostgz boostgz.cc -lboost_iostreams-mt
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
using namespace std;
static int read_file(std::string& buf, const char *fn)
{
ifstream file(fn, ios_base::in | ios_base::binary);
boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
in.push(boost::iostreams::gzip_decompressor());
in.push(file);
std::istream inf(&in);
while (inf.good()) {
char tmpbuf[8192];
inf.read(tmpbuf, sizeof(tmpbuf));
buf.append(tmpbuf, inf.gcount());
}
return 0;
}
static void add_data(std::string& buf, const char *data)
{
buf += data;
buf += "\n";
}
static void write_file(std::string& buf, const char *fn)
{
ofstream file(fn, ios_base::out | ios_base::binary | ios_base::trunc);
boost::iostreams::filtering_streambuf<boost::iostreams::output> out;
out.push(boost::iostreams::gzip_compressor());
out.push(file);
std::ostream outf(&out);
outf.write(buf.c_str(), buf.size());
}
int main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "usage: %s [string to add] [file.gz]\n",
argv[0]);
return 1;
}
const char *data = argv[1];
const char *fn = argv[2];
std::string buf;
read_file(buf, fn);
add_data(buf, data);
write_file(buf, fn);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment