linux poison RSS
linux poison Email

Perl Script - Reading / Writing Binary files

A binary file is a computer file that is not a text file; it may contain any type of data, encoded in binary form for computer storage and processing purposes.

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.

Below sample Perl script demonstrate the usage of reading / writing the binary files using binary mode.

Source: binary.pl
#!/usr/bin/perl

$buffer = "";
$infile = "binary.dat";
$outfile = "binary_copy.dat";
open (INFILE, "<", $infile) or die "Not able to open the file. \n";
open (OUTFILE, ">", $outfile) or die "Not able to open the file for writing. \n";
binmode (INFILE);
binmode (OUTFILE);

#Read file in 64K blocks
while ( (read (INFILE, $buffer, 65536)) != 0 ) {
  print OUTFILE $buffer;


close (INFILE) or die "Not able to close the file: $infile \n";
close (OUTFILE) or die "Not able to close the file: $outfile \n";

print "Successfully able to copy the binary file to : $outfile \n";

Output: perl binary.pl
Successfully able to copy the binary file to : binary_copy.dat





0 comments:

Post a Comment

Related Posts with Thumbnails