char_count.rb

#文字数カウント
#Usage: ruby char_count.rb TEXT_FILE
  
  require 'jcode'
  require 'auto_kconv'
  class NoFileError < RuntimeError ; end
  
  
begin
  name = ARGV.shift
  raise(ArgumentError, "引数がありません") if name.nil?
  raise(ArgumentError, "引数が多すぎます") unless ARGV.empty?
  unless File.exist?(name)
    raise(NoFileError, "#{name}: そのようなファイルは存在しません")
  end
  
rescue NoFileError => exception
  STDERR.puts exception.message
  exit(1)
  
rescue => exception
  STDERR.puts "#{exception.class}: #{exception.message}"
  exit(1)
  
end
  
  ALL, ASCII, WIDE = 0, 1, 2
  count = [0, 0, 0]
  File.open(name, "r").each do |line|
    line.akconv.each_char do |ch|
      if ch.length == 1
        count[ASCII] += 1
      else
        count[WIDE] += 1
      end
    end
  end
  count[ALL] = count[ASCII] + count[WIDE]
  
  
  STDOUT.puts "#{name}: 計 #{count[ALL]} 文字"
  STDOUT.puts "\t(半角: #{count[ASCII]}  全角: #{count[WIDE]})"