简体   繁体   English

为什么我不能打开 Perl 的 readdir 返回的文件?

[英]Why can't I open files returned by Perl's readdir?

Well, I know this is another newbie question but I'm very frustrated and I'm looking to be enlightened again.好吧,我知道这是另一个新手问题,但我非常沮丧,我希望再次开悟。 With the guidance of you guys, I've already learnt how to use the glob function to read the contents of each file in a directory.在你们的指导下,我已经学会了如何使用 glob 函数来读取目录中每个文件的内容。 Now I'm trying the readdir-foreach combination to do the same thing but I keep receiving "Cannot open file: Permission denied" error.现在我正在尝试使用 readdir-foreach 组合来做同样的事情,但我一直收到“无法打开文件:权限被拒绝”错误。 Why is this happening with the same directory , the same files and the same me as Administrator.为什么在相同的目录、相同的文件和与管理员相同的我中发生这种情况。 Can someone kindly show me what I'm doing wrong?有人可以告诉我我做错了什么吗? Thanks.谢谢。

The following code uses the glob function and it works:下面的代码使用了 glob 函数,它可以工作:

#! perl
my $dir = 'f:/corpus/';
my @files = glob "$dir/*";
foreach my $file (@files) {
open   my $data, '<',"$file" or die "Cannot open FILE";
while(<$data>) {
...}

The following code fails and the error message says "Cannot open FILE: Permission denied".以下代码失败,错误消息显示“无法打开文件:权限被拒绝”。 But why?但为什么?

#! perl
my $dir = 'f:/corpus/';
opendir (DIR,'f:/corpus/') or die "Cannot open directory:$!";
my @files=readdir(DIR);
closedir DIR;
foreach my $file (@files) {
open   my $data, '<',"$file" or die "Cannot open FILE:$!";
while(<$data>) {
...}

The readdir() function returns only the file's name, not a full path. readdir()函数只返回文件名,而不是完整路径。 So you are trying to open eg "foo.txt" instead of "f:\\corpus\\foo.txt".所以你试图打开例如"foo.txt"而不是“f:\\corpus\\foo.txt”。

You should keep in mind that readdir returns directory names and file names.您应该记住readdir返回目录名文件名。 Most likely you are attempting to open one of the special directory entries .很可能您正试图打开一个特殊的目录条目. or .. which you generally need to filter out if you're using these functions:..如果您使用这些功能,通常需要过滤掉:

foreach my $f (@files)
{
    # skip special directory entries
    if ($f ne '.' && $f ne '..')
    {
        # ...
        print "$f\n";
    }
}

Also note Andy Ross ' suggestion that this will only return the relative path, not the full path.还要注意安迪罗斯的建议,这只会返回相对路径,而不是完整路径。

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

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