Create a zip file (tarball) from a folder

tar zip gzip flate2 compress

In the following example we can see how to create a tar.gz file from the content of a folder.

Dependencies

examples/create-zip-file/Cargo.toml

[package]
name = "create-zip-file"
version = "0.1.0"
edition = "2021"

[dependencies]
flate2 = "1.0.30"
tar = "0.4.40"

Code to create a tarball from the content of a folder

examples/create-zip-file/src/main.rs

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

use flate2::write::GzEncoder;
use flate2::Compression;
use tar::Builder;

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

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

    // check that the folder is not empty

    zip(filename, folder).unwrap();
}

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

    let tar_gz = std::fs::File::create(filename)?;
    let encoder = GzEncoder::new(tar_gz, Compression::default());

    let mut archive = Builder::new(encoder);
    archive.append_dir_all(".", folder)?;

    Ok(())
}

Author

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