2013年4月5日金曜日

php でファイルダンプ(クラス風味)

php もファイルダンプをクラス風味で作成してみた。これも標準ライブラリが例外を発生しないので例外処理については中途半端に印象だが、c++よりは記述しやすいかもしれない。
#! /usr/bin/php
<?php
class Dump {
   private $file;
   private $fp;

   public function __construct($name) {
      $this->file = $name;
   }

   public function adrdump($adr) {
      printf("%08x : ",$adr);
   }
   
   public function hexdump($buf) {
      $out = ""; $cnt = 0;
      foreach (unpack("C*",$buf) as $x) {
         if ($cnt == 8) { $out .= "- ";}
         $out .= sprintf("%02x ",$x);
         $cnt++;
      }
      printf("%-50s",$out);
   }
   
   public function chrdump($buf) {
      $out = "";
      foreach (unpack("C*",$buf) as $x) {
         (0x00 <= $x && $x <= 0x1f) || 0x7f <= $x ?
            $out .= "." : $out .= sprintf("%c",$x);
      }
      printf("| %-16s\n",$out);
   }

   public function display() {
      $fp = fopen($this->file,"r");
      if (!$fp) {
          throw new Exception("ファイルオープンエラー");
      }
      
      $cnt = 0;
      while($buf = fread($fp, 16)) {
         $this->adrdump($cnt*16);
         $this->hexdump($buf);
         $this->chrdump($buf);
      
         $cnt++;
      }
      if ($fp) fclose($fp);
   }
}

if ($argc != 2) {
   printf("Usage : test02.php file\n");
   exit(1);
}

try {
   $dump = new Dump($argv[1]);
   $dump->display();
}
catch(Exception $e) {
   printf("エラー:%s\n",$e->getMessage());
   exit(1);
}
exit(0);
?>

0 件のコメント:

コメントを投稿