Perl Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 5.00

Copy.pl - Copying Binary Files

This section provides a tutorial example of copying a file in binary mode using the binmode() function on input and output.

As a simple example program of input and output data in binary mode, I wrote Copy.pl to copy binary files:

#- Copy.pl
#- Copyright (c) 1995 by Dr. Herong Yang, http://www.herongyang.com/
#
   ($in, $out) = @ARGV;
   die "Missing input file name.\n" unless $in;
   die "Missing output file name.\n" unless $out;
   $byteCount = 0;
   open(IN, "< $in");
   binmode(IN);
   open(OUT, "> $out");
   binmode(OUT);
   while (read(IN,$b,1)) {
      $byteCount++;
      print(OUT $b);
   }
   close(IN);
   close(OUT);
   print "Number of bytes copied = $byteCount\n";
   exit;

To test this program, I used the following commands:

>copy c:\winnt\system32\mem.exe mem.exe
        1 file(s) copied.

>Copy.pl mem.exe mem_copy.exe
Number of bytes copied = 39386

>mem_copy
    655360 bytes total conventional memory
    655360 bytes available to MS-DOS
    633776 largest executable program size

   1048576 bytes total contiguous extended memory
         0 bytes available contiguous extended memory
    941056 bytes available XMS memory
           MS-DOS resident in High Memory Area

Sections in This Chapter

binmode() - Opening Files for Binary Input

binmode() - Opening Files for Binary Output

Copy.pl - Copying Binary Files

Bin2Hex.pl - Converting Binary Data to Hex Numbers

Dr. Herong Yang, updated in 2008
Copy.pl - Copying Binary Files