>try.txt") or die ("Cant o-6ren">
gpt4 book ai didi

perl:在第 N 个位置写入文件

转载 作者:行者123 更新时间:2023-12-04 17:28:15 26 4
gpt4 key购买 nike

我正在尝试在第 N 个位置写入文件。我试过下面的例子,但它写在最后。请帮助实现这一目标。

#!/usr/bin/perl

open(FILE,"+>>try.txt")
or
die ("Cant open file try.txt");

$POS=5;

seek(FILE,$POS,0);

print FILE "CP1";

最佳答案

如果我理解正确,如果文件内容是

123456789

you want to change that to

1234CP157689

You cannot achieve that using modes supplied to open (regardless of programming language).

You need to open the source file and another temporary file (see File::Temp. Read up to the insertion point from the source and write the contents to the temporary file, write what you want to insert, then write the remainder of the source file to the temporary file, close the source and rename the temporary to the source.

If you are going to do this using seek, both files must be opened in binary mode.

Here is an example using line oriented input and text mode:

#!/usr/bin/perl

use strict; use warnings;
use File::Temp qw( :POSIX );

my $source = 'test.test';
my $temp = tmpnam;

open my $source_h, '<', $source
or die "Failed to open '$source': $!";

open my $temp_h, '>', $temp
or die "Failed to open '$temp' for writing: $!";

while ( my $line = <$source_h> ) {
if ( $line =~ /^[0-9]+$/ ) {
$line = substr($line, 0, 5) . "CP1" . substr($line, 5);
}
print $temp_h $line;
}

close $temp_h
or die "Failed to close '$temp': $!";

close $source_h
or die "Failed to close '$source': $!";

rename $temp => $source
or die "Failed to rename '$temp' to '$source': $!";

关于perl:在第 N 个位置写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3667176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com