type count = { mutable chars : int; mutable lines : int; mutable words : int; };; let new_count() = {chars = 0; lines = 0; words = 0};; let total = new_count();; let cumulate wc = total.chars <- total.chars + wc.chars; total.lines <- total.lines + wc.lines; total.words <- total.words + wc.words;; let rec counter ic iw wc = let c = input_char ic in wc.chars <- wc.chars + 1; match c with | ' ' | '\t' -> if iw then wc.words <- wc.words + 1 else (); counter ic false wc | '\n' -> wc.lines <- wc.lines + 1; if iw then wc.words <- wc.words + 1 else (); counter ic false wc | c -> counter ic true wc;; let count_channel ic wc = try counter ic false wc with | End_of_file -> cumulate wc; close_in ic;; let output_results s wc = Printf.printf "%7d%8d%8d %s\n" wc.lines wc.words wc.chars s;; let count_file file_name = try let ic = open_in file_name in let wc = new_count() in count_channel ic wc; output_results file_name wc; with Sys_error s -> print_string s; print_newline(); exit 2;; let main () = let nb_files = Array.length Sys.argv - 1 in if nb_files > 0 then begin for i = 1 to nb_files do count_file Sys.argv.(i) done; if nb_files > 1 then output_results "total" total; end else begin let wc = new_count() in count_channel stdin wc; output_results "" wc; end; exit 0;; main();;