使用 camlzip 解壓縮包含多個檔案的 ZIP 壓縮檔
任務
壓縮 / 解壓縮包含多個檔案的 ZIP 壓縮檔
使用的 Opam 套件
- camlzip 測試版本:1.11 — 使用的函式庫:camlzip
程式碼
當從 ZIP 壓縮檔解壓縮檔案時,我們需要建立它所在的目錄(如果目錄尚不存在)。
let create_dir_if_not_exists filename =
let rec aux_ensure base l =
if not (Sys.file_exists base) then
Sys.mkdir base 0o755
else
if not (Sys.is_directory base) then
failwith "Error, file exists instead of a directory";
match l with
| [] -> failwith "Should not happen"
| [ _filename ] -> ()
| directory :: l' -> aux_ensure (base ^ "/" ^ directory) l'
in
match String.split_on_char '/' filename with
| [ ] -> failwith "Should not happen (null filename)"
| [ _filename ] -> ()
| directory :: l -> aux_ensure directory l
開啟 ZIP 檔案以進行讀取。
let unzip zip_filename =
let zip = Zip.open_in zip_filename in
迭代 ZIP 檔案中的所有條目。
let entries = Zip.entries zip in
entries
|> List.iter (fun entry ->
Printf.printf "%s\n" entry.Zip.filename;
create_dir_if_not_exists entry.Zip.filename;
如果條目是目錄,則只需建立目錄。
if entry.Zip.is_directory then
Sys.mkdir entry.Zip.filename 0o755
如果條目是一般檔案,則將其解壓縮。
else
Zip.copy_entry_to_file
zip
entry
entry.Zip.filename);
最後,關閉 ZIP 檔案。
Zip.close_in zip