Dup Ver Goto 📝

Unzip in Rust 001

PT2/lang/rust/examples/archive rust zip does not exist
To
58 lines, 166 words, 1583 chars Page 'Unzip_001' does not exist.

Based on examples from Chatgpt, one for the unzip, and the other for getting command line args via env.

[package]
name = "zip1"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
zip = "0.5"
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use zip::read::{ZipArchive, ZipFile};

fn unzip_file(zip_file_path: &str, output_dir: &str) -> Result<(), Box<dyn std::error::Error>> {
    let file = File::open(zip_file_path)?;
    let reader = BufReader::new(file);
    let mut archive = ZipArchive::new(reader)?;

    for i in 0..archive.len() {
        let mut file = archive.by_index(i)?;
        let file_path = format!("{}/{}", output_dir, file.name());

        if file.is_dir() {
            std::fs::create_dir_all(&file_path)?;
        } else {
            if let Some(parent_dir) = std::path::Path::new(&file_path).parent() {
                std::fs::create_dir_all(parent_dir)?;
            }

            let mut outfile = File::create(&file_path)?;
            std::io::copy(&mut file, &mut outfile)?;
        }
    }

    Ok(())
}

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() >= 3 {
        let zip_file_path = &args[1];
        let output_dir = &args[2];
        match unzip_file(zip_file_path, output_dir) {
            Ok(_) => println!("Extraction successful!"),
            Err(err) => eprintln!("Error: {}", err),
        }
    } else {
        println!("Invalid args");
    }
}