Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

stat question

Status
Not open for further replies.

zfang

Programmer
Apr 3, 2002
23
US
Hi:

I tried to use stat() function to retrive properties of a file, e.g. last accessed time, last modified time etc.
It works on some of the files of one directory, but not all.

Here is the code:

#/usr/local/bin/perl
use strict;
my $directory = "here is the directory";
opendir THISDIR, $directory or die "cannot open the directory: $!";
my @allFiles = readdir THISDIR;
foreach my $file (@allFiles)
{
my @fileAttributes = stat($file);
#here it's supposed to print a numebr related to
#the last modification time. but for some files this attribute is null, some files have the number.
print "fileAttributes=$fileAttributes[8]\n";
}
closedir(THISDIR);

The code is supposed to print a number for each file, which is related to the last midified time. However, that number can be printed for some file, but others are null.
Could anyone give me any advices why that happedned?

Thanks a lot,

George
 
The problem with your code is, you're also trying to stat directories "." and "..". Instead, consider the following code using "IO::Dir" and "Fcntl"

Code:
tie my %files, "IO::Dir", $directory or die $!;
while ( my ($file, $stat) = each %files ) {
      S_ISDIR($stat->mode) && next;
      print "Modification date for $file is ", 
               localtime($stat->mtime), "\n";
}

IO::Dir returns a hash of all the contents of the directory, keys being the name of the file/directory, and values being object oriented version of stat. More user friendly, more obvious and more ellegant :).

Sherzod Ruzmetov
 
A small correction. Replace "localtime($stat->mtime)" with "scalar(localtime($stat->mtime))".

Here is a working full script you can simply copy/paste and test out:

Code:
#!/usr/bin/perl -w

use strict;
use IO::Dir;
use Fcntl ':mode';

tie my %files, "IO::Dir", '.'  or die $!;
while ( my ($file, $stat) = each %files ) {
      S_ISDIR($stat->mode) && next;
      printf("Modification date for %10s is %29s\n", $file, scalar localtime($stat->mtime));
}
untie(%files);

Sherzod Ruzmetov
 
Hi, Sherzod:

Thanks for your reply. I could not test your code yet because the IO::Dir is not installed on our machine. I need to ask the sys admin to install it.
By the way, I got one solution from the another Perl forum.

Replace
my @fileAttributes = stat($file);
in my code with
my @fileAttributes = stat("$directory/$file");
then it works.

Have a nice day,

George
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top