edem
edem

Reputation: 3272

Read and write file bit by bit

There is a .jpg file for example or some other file. I want to read it bit by bit. I do this:

open(FH, "<", "red.jpg") or die "Error: $!\n";
my $str;
while(<FH>) {
    $str .= unpack('B*', $_);
}
close FH;

Well it gives me $str with 0101001 of the file. After that I do this:

open(AB, ">", "new.jpg") or die "Error: $!\n";
binmode(AB);
print AB $str;
close AB;

but it doesn't work.

How can I do it? and how to do that that it would work regardless of byte order(cross-platform)?

Upvotes: 2

Views: 1640

Answers (1)

ikegami
ikegami

Reputation: 386696

Problems:

  1. You're didn't use binmode when reading too.
  2. It makes no sense to read a binary file line by line since they don't have lines.
  3. You're needlessly using global variables for your file handles.
  4. And the one that answers your question: You didn't reverse the unpack.

open(my $FH, "<", "red.jpg")
   or die("Can't open red.jpg: $!\n");
binmode($FH);
my $file; { local $/; $file = <$FH>; }
my $binary = unpack('B*', $file);

open(my $FH, ">", "new.jpg")
   or die("Can't create new.jpg: $!\n");
binmode($FH);
print $FH pack('B*', $binary);

Upvotes: 5

Related Questions