lz77/bin/main.ml

38 lines
1.5 KiB
OCaml

let read_file path =
let ic = open_in_bin path in
let len = in_channel_length ic in
let s = really_input_string ic len in
close_in ic; Bytes.of_string s
let write_file path b =
let oc = open_out_bin path in
output_string oc (Bytes.to_string b);
close_out oc
let () =
match Array.to_list Sys.argv with
| _ :: mode :: in_path :: out_path :: [] ->
(try
let input = read_file in_path in
if mode = "compress" then begin
let out = Encoder.compress input in
write_file out_path out;
Printf.printf "Original: %d bytes\n" (Bytes.length input);
Printf.printf "Compressed: %d bytes\n" (Bytes.length out);
let ratio = 100.0 *. (float_of_int (Bytes.length out)) /. (float_of_int (Bytes.length input)) in
Printf.printf "Compression ratio: %.2f%%\n" ratio
end else if mode = "decompress" then begin
let out = Decoder.decompress input in
write_file out_path out;
Printf.printf "Decompressed to %d bytes\n" (Bytes.length out)
end else begin
prerr_endline "Invalid mode: use 'compress' or 'decompress'";
exit 2
end
with
| Sys_error e -> prerr_endline ("I/O error: " ^ e); exit 1
| Failure e -> prerr_endline ("Error: " ^ e); exit 1
| Invalid_argument e -> prerr_endline ("Invalid input: " ^ e); exit 1
)
| _ -> prerr_endline "Usage: lz77-cli (compress|decompress) <in> <out>"; exit 2