Wednesday, December 26, 2012

Perl 에서 Binary File 읽고 쓰기 샘플 코드

USAGE :
 $ ./test.pl -w  
 $ ./test.pl -r  
Code :

#!/usr/bin/perl -w
 use strict;
 use warnings;

 main("mytest.bin");  
   
 sub main  
 {  
      print("--------------------------------------------------\n");  
      my ($mode) = @ARGV;  
      my $numArgv = @ARGV;  
      if($numArgv == 0){  
           print("arguments : -r to read and -w to write\n");  
           exit(0);  
      }  
      else{  
           if($mode =~ /^-w$/i){  
                writeBinFile(@_);  
           }  
           elsif($mode =~ /^-r$/i){  
                readBinFile(@_);  
           }  
      }  
      exit 0;  
 }  
   
 sub writeBinFile  
 {  
      print("Write mode.\n");  
   
      my (($outfile), $buffer) = (@_, undef);  
      my ($num_bytes, $errmsg) = (1024, "Couldn't write to $outfile");  
        
      open (OUTFILE, ">$outfile") or die "$errmsg : $!";  
      binmode (OUTFILE);  
        
      $buffer .= pack 'B8', "11110000"; # 240 = 128 + 64 + 32 + 16  
      $buffer .= pack 'B8', "11110001"; # 241  
      $buffer .= pack 'B8', "11110010"; # 242  
      $buffer .= pack 'B8', "11110011"; # 243  
      $buffer .= pack 'C1', 0;  
        
      $buffer .= pack 'C1', 200; # 200  
      $buffer .= pack 'H4', "FEFF"; # 254, 255  
      $buffer .= pack 'C1', 0;  
   
      $buffer .= pack 'A2', "ab";  
      print OUTFILE $buffer;  
      close OUTFILE;  
        
      print("Write success.\n");  
 }  
   
 sub readBinFile  
 {  
      print("Read mode.\n");  
        
      my (($infile), $buffer) = (@_, undef);  
      my ($num_bytes, $errmsg) = (1024, "Couldn't read from $infile.");  
        
      open (INFILE, "$infile") or die "$errmsg : $!";  
      binmode (INFILE);  
        
      my ($buf, $data, $n);  
      for (; ($n = read INFILE, $data, 65536) != 0; $buf .= $data){  
           print "Reading $n bytes from file: $infile\n";  
      }  
      close(INFILE);  
   
      my @buffer;  
      @buffer = unpack('(C1)*', $buf);  
      foreach (@buffer){  
           print();  
           print "\n";  
      }  
      my $sizeBuffer = @buffer;       
      print "buffer size is $sizeBuffer.\n";  
 }  
Result :
 Read mode.  
 Reading 11 bytes from file: mytest.bin  
 240  
 241  
 242  
 243  
 0  
 200  
 254  
 255  
 0  
 97  
 98  
 buffer size is 11.  
키워드 : Read, Write, 바이너리 파일, 이진파일, binmode

No comments:

Post a Comment