wcコマンド

let version = "0.1"
let display_byte_count = ref false
let display_line_count = ref false
let display_word_count = ref false
let filenames = ref []

let spec = [("-c", Arg.Set display_byte_count, "Display the byte counts.");
	    ("-l", Arg.Set display_line_count, "Display the line counts.");
	    ("-w", Arg.Set display_word_count, "Display the word counts.");
	    ("-version", 
	     Arg.Unit
	       (fun () -> Printf.printf "wc in OCaml ver: %s\n" version),
	     "Display version information.")]

let count filename =
  let cnl = open_in filename in
  let byte_count = ref 0 in
  let line_count = ref 0 in
  let word_count = ref 0 in
  (try while true do
    let input = input_line cnl in
    line_count := !line_count + 1;
    word_count := !word_count + 
	List.length (Str.split (Str.regexp "[ \t]+") input);
    byte_count := !byte_count + String.length input;
  done with End_of_file -> close_in cnl);
  if !display_line_count then Printf.printf " %6d " !line_count;
  if !display_word_count then Printf.printf " %6d " !word_count;
  if !display_byte_count then Printf.printf " %6d " !byte_count;
  Printf.printf "%s\n" filename

let _ = 
  Arg.parse spec
    (fun s -> filenames := s :: !filenames)
    "Usage: wc [-c] [-l] [-w] [-help] [-version] filename ...";
  if not (!display_byte_count) && not (!display_line_count) && 
    not (!display_word_count) then (
    display_byte_count := true;
    display_line_count := true;
    display_word_count := true);
  List.iter count (List.rev !filenames)