Herong's Tutorial Notes on Perl - Part A
Dr. Herong Yang, Version 4.09

Input and Output in Binary Mode

Part:   1   2 

This chapter describes:

  • How to open files for input in binary mode.
  • How to open files for output in binary mode.
  • Example program to copy binary files
  • Example program to convert binary data to hex numbers.

Opening Files for Binary Input

If you want to open a file and read its content in binary mode, you should use the following functions:

  • open() to open the file to a file handle.
  • binmode() to set the file handle to binary mode.
  • read() to read data from the file handle.
  • close() to close the file handle.

Descriptions and sample codes of open() and close() are in the previous chapter.

The syntax of binmode() is very simple:

   binmode(file_handle);

The syntax of read() is more complex:

rc = read(file_handle, buffer, length, offset);
rc = read(file_handle, buffer, length);

where "buffer" is a scalar variable where the inputted bytes will be stored; "length" is the number of bytes requested to be inputted; "rc" is the actual number of bytes inputted; "offset" is an optional value to specify where in the scalar variable to begin to store the inputted bytes.

Opening Files for Binary Output

If you want to open a file and write binary data to it, you should use the following functions:

  • open() to open the file to a file handle.
  • binmode() to set the file handle to binary mode.
  • print() to write data to the file handle.
  • close() to close the file handle.

Note that the print() function can be used in both binary mode and text mode. In binary mode, print() will not convert \n to \r\n in Windows system.

Copy Binary Files - Copy.pl

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
#
   ($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

(Continued on next part...)

Part:   1   2 

Dr. Herong Yang, updated in 2006
Herong's Tutorial Notes on Perl - Part A - Input and Output in Binary Mode