Tweet

How do I write binary files on a non-Unix OS?

The runtime libraries of some operating systems make a distinction between binary and text files. In these operating systems, if you write binary data to a file it will come out as gumph.

The Solution

Immediately after you call open on the file, use the binmode function:

    open (OUTFILE, ">$filename") or die "Couldn't open $filename for writing: $!";
    binmode OUTFILE;

Then just print to the file like usual:

    print OUTFILE $binary_data;

Here's a full example which reads in the file test.jpg and prints it to test2.jpg:

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

    my $buffer;
    my $num_bytes = 1024;
    my $infile = "test.jpg";
    my $outfile = "test2.jpg";

    open (INFILE, $infile) or die "Couldn't open $infile for reading: $!";
    open (OUTFILE, ">$outfile") or die "Couldn't open $outfile for writing: $!";

    binmode(INFILE);
    binmode (OUTFILE);

    while (read(INFILE, $buffer, $num_bytes)) {
        print OUTFILE $buffer;
    }

    close INFILE;
    close OUTFILE;

    exit 0;

See also

    perldoc -f binmode
    perldoc -f open
Revision: 1.5 [Top]