Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Working with Gzip

Decompress a gzip file

flate2-badge cat-compression-badge

Decompresses a single gzip-compressed file input.txt.gz into input.txt in the current working directory. Unlike decompressing a tarball, this reads plain (non-archive) gzip data, such as a single log or text file.

Wraps a File in a GzDecoder and copies the decompressed bytes into the destination file with io::copy.

use std::fs::File;
use std::io;
use flate2::read::GzDecoder;

fn main() -> Result<(), io::Error> {
    let input = File::open("input.txt.gz")?;
    let mut decoder = GzDecoder::new(input);
    let mut output = File::create("input.txt")?;
    io::copy(&mut decoder, &mut output)?;
    Ok(())
}

Compress a file with gzip

flate2-badge cat-compression-badge

Compresses input.txt into input.txt.gz in the current working directory.

Wraps a File in a GzEncoder configured with a Compression level, then copies the contents of the source file into the encoder with io::copy, transparently compressing the data as it is written to input.txt.gz.

use std::fs::File;
use std::io;
use flate2::write::GzEncoder;
use flate2::Compression;

fn main() -> Result<(), io::Error> {
    let mut input = File::open("input.txt")?;
    let output = File::create("input.txt.gz")?;
    let mut encoder = GzEncoder::new(output, Compression::default());
    io::copy(&mut input, &mut encoder)?;
    encoder.finish()?;
    Ok(())
}