如何确定Perl文件句柄是读取还是写入句柄?

时间:2009-03-23 04:15:09

标签: perl filehandle

您将获得IO::File个对象或typeglob(\*STDOUTSymbol::symbol_to_ref("main::FH"));您将如何确定它是读取还是写入句柄?无法扩展该界面以传递此信息(我会覆盖close以在实际关闭之前添加对flushsync的调用。

目前我正在尝试flushsync文件句柄并忽略错误"Invalid argument"(这是我尝试flush或{{1}时获得的错误一个读文件句柄):

sync

1 个答案:

答案 0 :(得分:7)

看看fcntl选项。也许F_GETFLO_ACCMODE

编辑:我做了一些谷歌搜索和午餐游戏,这里有一些可能是非便携式的代码,但它适用于我的Linux机箱,可能还有任何Posix系统(甚至Cygwin,谁知道?)。

use strict;
use Fcntl;
use IO::File;

my $file;
my %modes = ( 0 => 'Read only', 1 => 'Write only', 2 => 'Read / Write' );

sub open_type {
    my $fh = shift;
    my $mode = fcntl($fh, F_GETFL, 0);
    print "File is: " . $modes{$mode & 3} . "\n";
}

print "out\n";
$file = new IO::File();
$file->open('> /tmp/out');
open_type($file);

print "\n";

print "in\n";
$file = new IO::File();
$file->open('< /etc/passwd');
open_type($file);

print "\n";

print "both\n";
$file = new IO::File();
$file->open('+< /tmp/out');
open_type($file);

示例输出:

$ perl test.pl 
out
File is: Write only

in
File is: Read only

both
File is: Read / Write
相关问题