问题
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. Now I'm trying the readdir-foreach combination to do the same thing but I keep receiving "Cannot open file: Permission denied" error. 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:
#! 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>) {
...}
回答1:
The readdir()
function returns only the file's name, not a full path. So you are trying to open e.g. "foo.txt"
instead of "f:\corpus\foo.txt".
回答2:
You should keep in mind that readdir
returns directory names and file names. 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.
来源:https://stackoverflow.com/questions/1557942/why-cant-i-open-files-returned-by-perls-readdir