在使用tar进行压缩的时候如何使用绝对地址作为输入和输出地址?

运行完毕直接就报错是 在设置路径时,档案中的路径必须相对, 但我想要使用绝对路径. 希望大佬们不吝解答

运行结果

C:/Users/BORBER/.cargo/bin/cargo.exe run --color=always --package rust_test --bin rust_test
    Finished dev [unoptimized + debuginfo] target(s) in 0.03s
     Running `target\debug\rust_test.exe`
Error: Custom { kind: Other, error: "paths in archives must be relative when setting path for " }
error: process didn't exit successfully: `target\debug\rust_test.exe` (exit code: 1)

main.rs

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

fn main()  -> Result<(), std::io::Error> {
    // Create Gzip file
    let compressed_file = File::create("backup.tar.gz")?;
    let mut encoder = GzEncoder::new(compressed_file, Compression::default());

    {
// Create tar archive and compress files
        let mut archive = tar::Builder::new(&mut encoder);
        archive.append_dir_all("C:\\Users\\BORBER\\game", "C:\\Users\\BORBER\\game\\Baldurs.Gate.Enhanced.Edition.v2.6.6.0.Multi.15")?;
    }

// Finish Gzip file
    encoder.finish()?;
    Ok(())
}

cargo.toml

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

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

[dependencies]
tar = "0.4"
flate2 = { version = "1.0.17", features = ["zlib-ng-compat"], default-features = false }
最佳答案

两个地方改下

  1. 创建压缩文件改成 绝对路径
    let compressed_file = File::create(r"C:\Users\BORBER\game\backup.tar.gz")?;
  2. 要压缩的文件 第一个参数不要用绝对路径
    archive.append_dir_all(".", r"C:\Users\BORBER\game\Baldurs.Gate.Enhanced.Edition.v2.6.6.0.Multi.15")?;
1个月前 评论
讨论数量: 3

两个地方改下

  1. 创建压缩文件改成 绝对路径
    let compressed_file = File::create(r"C:\Users\BORBER\game\backup.tar.gz")?;
  2. 要压缩的文件 第一个参数不要用绝对路径
    archive.append_dir_all(".", r"C:\Users\BORBER\game\Baldurs.Gate.Enhanced.Edition.v2.6.6.0.Multi.15")?;
1个月前 评论

感谢, 我后来也发现了, 我理解错了参数的意义,

这是我后来的代码

use std::fs::File;
use flate2::Compression;
use flate2::write::GzEncoder;
use flate2::read::GzDecoder;
use tar::Archive;

fn main()  -> Result<(), std::io::Error> {
    pack("backup.tar.gz", "data", r"C:\Users\BORBER\CLionProjects\RustTest\data")?;
    unpack("backup.tar.gz", r"C:\Users\BORBER\Desktop")
}

fn pack(output: &str,path: &str, src_path: &str) -> Result<(), std::io::Error> {
    // Create Gzip file
    let compressed_file = File::create(output)?;
    let mut encoder = GzEncoder::new(compressed_file, Compression::default());

    {
    // Create tar archive and compress files
        let mut archive = tar::Builder::new(&mut encoder);
        archive.append_dir_all(path, src_path)?;
    }
    // Finish Gzip file
    encoder.finish()?;
    Ok(())
}

fn unpack(path: &str, dst: &str) -> Result<(), std::io::Error>{
    let tar_gz = File::open(path)?;
    Archive::new(GzDecoder::new(tar_gz)).unpack(dst)?;
    Ok(())
}

1个月前 评论
thomas007 1个月前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!