Rust如何解压zip文件
在Rust中如何解压zip文件?我尝试使用zip这个crate,但遇到了一些问题。具体来说,当读取压缩包内的文件时,总是报"invalid zip header"错误。我的代码大致是这样的:
use std::fs::File;
use zip::ZipArchive;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let file = File::open("test.zip")?;
let mut archive = ZipArchive::new(file)?;
// ...解压操作
}
请问:
- 这是正确的使用方式吗?
- 为什么会出现无效的zip头错误?
- 是否有更简单的方法来解压zip文件?
2 回复
使用 zip 库。先添加依赖:
[dependencies]
zip = "0.6"
示例代码:
use std::fs::File;
use zip::ZipArchive;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let file = File::open("test.zip")?;
let mut archive = ZipArchive::new(file)?;
for i in 0..archive.len() {
let mut file = archive.by_index(i)?;
let outpath = file.sanitized_name();
// 解压到文件
let mut outfile = File::create(&outpath)?;
std::io::copy(&mut file, &mut outfile)?;
}
Ok(())
}
在Rust中解压zip文件,可以使用zip库。以下是详细步骤和示例代码:
步骤
- 添加依赖:在
Cargo.toml中添加zip库。 - 读取zip文件:使用
File::open打开zip文件。 - 创建zip存档对象:通过
ZipArchive::new从文件创建存档。 - 遍历并解压文件:逐个提取文件到指定目录。
示例代码
use std::fs::{self, File};
use std::io::{self, Read, Write};
use zip::ZipArchive;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let file = File::open("example.zip")?;
let mut archive = ZipArchive::new(file)?;
// 创建解压目录
fs::create_dir_all("output")?;
for i in 0..archive.len() {
let mut file = archive.by_index(i)?;
let outpath = match file.enclosed_name() {
Some(path) => path.to_owned(),
None => continue,
};
// 处理目录
if file.name().ends_with('/') {
fs::create_dir_all(&outpath)?;
} else {
// 创建父目录
if let Some(p) = outpath.parent() {
if !p.exists() {
fs::create_dir_all(p)?;
}
}
// 写入文件
let mut outfile = File::create(&outpath)?;
io::copy(&mut file, &mut outfile)?;
}
}
Ok(())
}
说明
- 依赖:在
Cargo.toml中添加:[dependencies] zip = "0.6" - 错误处理:使用
?操作符简化错误传播。 - 安全性:
enclosed_name方法可防止路径遍历攻击。 - 目录处理:自动创建缺失的父目录。
运行此代码后,example.zip的内容将被解压到output目录中。

