繁体   English   中英

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

[英]How can I open a binary file in Perl, change ONLY the first byte, and write it back out?

非常类似于在C中更改文件中的一个字节 ,但在Perl中而不是C中。

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

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"; 

有很多方法可以做到。 一种有效的方法是以随机访问模式打开文件, 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM