0

这就是我想要实现的目标:

open(my $file,">>","/var/opt/input.txt");
if("/var/opt/input.txt" is opened sucessfully)
{
  do some tasks;
}
else
{
  do some other task;
}
4

3 回答 3

5

所以你想打开一个文件进行追加,但前提是它已经存在(所以不要创建它)。

一种方法确实是首先检查文件(不)是否存在,然后打开它。但是,由于文件可以在检查后立即创建,因此存在竞争条件!大多数情况下,这是一件罕见的事情,但是有一个竞争条件是不好的,并且总是必须避免,因为它会导致安静和神秘的错误。

sysopen当人们需要更详细的控制和灵活性时,这一要求就是一个很好的例子。直接做需要做的事

use Fcntl qw(O_WRONLY O_APPEND);  # to bring in symbolic constants

if ( sysopen(my $fh, $filename, O_WRONLY | O_APPEND) ) {  # fails if no file
    say $fh scalar localtime;                             # appends to file
}
elsif ($!{ENOENT}) {
    # The case to avoid, file doesn't exist ($!: "No such file or directory")
    warn "Can't sysopen $filename: $!";  
}
else { 
    # Some other error
    warn "Can't sysopen $filename: $!";
}

使用给定的标志组合,如果文件尚不存在,则 open 调用将失败。任何文件打开也可能以其他方式失败,因此我将检查文件是否缺失作为失败的原因(使用%!哈希)。如果这超出了您的需要,只需使用一个并从中else打印。$!

如果这是在模块中,请记住改为使用carp警告(需要use Carp;

请参阅perlopenut 中的sysopen及其部分,以及有用的Fcntl

于 2021-07-13T18:15:10.627 回答
3

open的文档中:

Open 成功时返回非零值,否则返回未定义值。

一种方法是直接openif子句中使用:

if (open(my $file, ">>", "input.txt"))
{
  #do some tasks;
}
else
{
  #do some other task;
}
于 2021-07-13T14:58:08.627 回答
3

正如其他人指出的那样,open()返回一个 true 或 false 值,指示文件是否已成功打开。但是,这是一个标准的文件处理功能,如果您尝试打开一个尚不存在的文件进行写入(或附加),则会为您创建该文件。听起来那不是你想要的。

因此,您需要在尝试打开文件之前检查该文件是否存在。Perl 有许多文件测试运算符可以帮助您。您可以使用-fwhich 检查文件是否存在。

my $file_name = '/var/opt/input.txt';

if (-f $file_name and open my $file, '>>', $file) {
  # File exists and was opened successfully
} else {
  # Either file doesn't exist or file can't be opened
}

您也可以将其拆分为两个单独的测试。

my $file_name = '/var/opt/input.txt';

if (-f $file_name) {
  if (open my $file, '>>', $file) {
    # File exists and was opened successfully
  } else {
    # File exists but can't be opened
  }
} else {
  # File doesn't exist
}
于 2021-07-13T17:29:35.067 回答