为什么我无法打开 Perl 的 readdir 返回的文件?
好吧,我知道这是另一个新手问题,但我非常沮丧,我希望再次受到启发。在你们的指导下,我已经学会了如何使用 glob 函数读取目录中每个文件的内容。现在我正在尝试 readdir-foreach 组合来做同样的事情,但我不断收到“无法打开文件:权限被拒绝”错误。为什么在相同的目录、相同的文件和相同的管理员身份下会发生这种情况。有人可以告诉我我做错了什么吗?谢谢。
以下代码使用 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>) {
...}
以下代码失败,错误消息显示“无法打开文件:权限被拒绝”。但为什么?
#! 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>) {
...}
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>) {
...}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
readdir()
函数仅返回文件名,而不返回完整路径。因此,您尝试打开例如"foo.txt"
而不是 "f:\corpus\foo.txt"。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".您应该记住,
readdir
返回目录名和文件名。您很可能正在尝试打开特殊目录条目.
或..
之一,如果您使用这些函数,通常需要过滤掉这些条目:另请注意 Andy Ross' 建议这只会返回相对路径,而不是完整路径。
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:Also note Andy Ross' suggestion that this will only return the relative path, not the full path.