如何在Perl中打开二进制文件,只更改第一个字节,然后将其写回?

时间:2010-03-17 17:13:34

标签: perl binaryfiles

Changing one byte in a file in C非常相似,但在Perl中而不是C。

如何在Perl中打开二进制文件,只更改第一个字节,然后将其写回来?

2 个答案:

答案 0 :(得分:12)

open my $fh, '+<', $file      or die "open failed: $!\n";
my $byte;
sysread($fh, $byte, 1) == 1   or die "read failed: $!\n";
seek($fh, 0, 0);
syswrite($fh, $new_byte) == 1 or die "write failed: $!\n";
close $fh                     or die "close failed: $!\n"; 

答案 1 :(得分:6)

有很多方法可以做到这一点。一种有效的方法是使用open $fh, '+<'随机访问模式打开文件:

my $first_byte = chr(14);      # or whatever you want the first byte to be
open my $fh, '+<', $the_file;
seek $fh, 0, 0;                # optional - cursor is originally set to 0
print $fh $first_byte;         # could also use  write  or  syswrite  functions
close $fh;