Unzip a file to the disk using Rust

tar zip unzip gzip flate2 compress

flate2 is a crate to compress and uncompress files using various compression algorithms.

tar is a crate to create tar files (aka. tarballs).

Combining the two could unzip and untar tar.gz file.

Note, we use the read::GzDecoder of flate2.

In another example we unzip a file that was embedded in the binary where we use another version of this struct.



name = "unzip-file"
version = "0.1.0"
edition = "2021"

flate2 = "1.0.30"
tar = "0.4.40"

Full example unzipping a file to the disk


use std::{error::Error, fs::create_dir_all, path::PathBuf};

use flate2::read::GzDecoder;
use std::{fs, io};
use tar::Archive;

fn main() {
    let args = std::env::args().collect::<Vec<String>>();
    if args.len() != 3 {
        eprintln!("Usage: {} FILENAME FOLDER", args[0]);
    let filename = PathBuf::from(&args[1]);
    let folder = PathBuf::from(&args[2]);
    if !filename.exists() {
        eprintln!("file {filename:?} does not exist");

    if folder.exists() {
        if !folder.is_dir() {
            eprint!("The second parameter {folder:?} is not a folder");
    if !folder.exists() {

   // check that the folder is empty

    unzip(filename, folder).unwrap();

fn unzip(filename: PathBuf, folder: PathBuf) -> Result<(), Box<dyn Error>> {
    println!("Unzipping {filename:?} to {folder:?}");

    let tar_gz = std::fs::File::open(filename)?;
    let tar = GzDecoder::new(tar_gz);
    let mut archive = Archive::new(tar);


Related Pages

Unzip a file that was embedded in the Rust application


Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo