首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何确定Perl文件句柄是读句柄还是写句柄?

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

Stack Overflow用户
提问于 2009-03-23 04:15:09
回答 1查看 1.8K关注 0票数 13

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

目前,我正在尝试对文件句柄执行flushsync操作,而忽略错误"Invalid argument" (这是我试图对文件句柄执行flushsync操作时得到的结果):

代码语言:javascript
复制
eval { $fh->flush; 1 } or do {
        #this seems to exclude flushes on read handles
        unless ($! =~ /Invalid argument/) {
                croak "could not flush $fh: $!";
        }
};

eval { $fh->sync; 1 } or do {
        #this seems to exclude syncs on read handles
        unless ($! =~ /Invalid argument/) {
                croak "could not sync $fh: $!";
        }
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2009-03-23 05:43:23

看看fcntl选项。也许是F_GETFLO_ACCMODE

编辑:我在午餐时搜索了一下,玩了玩,这里有一些可能不可移植的代码,但它可以在我的Linux机器上运行,也可能在任何Posix系统上运行(也许甚至是Cygwin,谁知道呢?)。

代码语言:javascript
复制
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);

输出示例:

代码语言:javascript
复制
$ perl test.pl 
out
File is: Write only

in
File is: Read only

both
File is: Read / Write
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/672214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档