Search code examples
c#c++deflate

Using DeflateStream in C++?


I'm currently trying to port some C# codes involving usage of DeflateStream into standard C++ without the support of .NET framework. One example of such function is:

public static byte[] ReadCompressed(this Stream stream)
{
    var reader = new BinaryReader(stream);
    int len = reader.ReadInt32();
    var array = new byte[len];
    var ds = new DeflateStream(stream, CompressionMode.Decompress);
    ds.Read(array, 0, len);
    ds.Close();
    return array;
}

Just wondering, Is there an easy way to port the above code into C++? Thanks!


Solution

  • You might want to use zlib. The easiest way to do that in C++ is to use the Boost wrapper for it.

    I'm not entirely sure what your example does, but here's how to read in a zlib-compressed file and write its contents to stdout (adapted from an example in the docs):

    namespace io = boost::iostreams;
    
    std::ifstream file("hello.z", std::ios_base::binary);
    io::filtering_streambuf<io::input> in;
    in.push(io::zlib_decompressor());
    in.push(file);
    io::copy(in, std::cout);