extract/
extract.rs

1//! Extracts files from an archive.
2//!
3//! To extract all files from an archive into the current directory, run:
4//!
5//! ```shell
6//! cargo run --example extract <path/to/archive.a>
7//! ```
8//!
9//! This is roughly equivalent to running:
10//!
11//! ```shell
12//! ar -x <path/to/archive.a>
13//! ```
14
15extern crate ar;
16
17use std::env;
18use std::fs::File;
19use std::io;
20use std::path::Path;
21use std::str;
22
23fn main() {
24    let num_args = env::args().count();
25    if num_args != 2 {
26        println!("Usage: extract <path/to/archive.a>");
27        return;
28    }
29
30    let input_path = env::args().nth(1).unwrap();
31    let input_path = Path::new(&input_path);
32    let input_file =
33        File::open(input_path).expect("failed to open input file");
34    let mut archive = ar::Archive::new(input_file);
35
36    while let Some(entry) = archive.next_entry() {
37        let mut entry = entry.expect("failed to parse archive entry");
38        let output_path = Path::new(
39            str::from_utf8(entry.header().identifier())
40                .expect("Non UTF-8 filename"),
41        )
42        .to_path_buf();
43        let mut output_file = File::create(&output_path)
44            .expect(&format!("unable to create file {:?}", output_path));
45        io::copy(&mut entry, &mut output_file)
46            .expect(&format!("failed to extract file {:?}", output_path));
47    }
48}