in reply to no size with stat and lstat in windows

I just ran the code below in a directory containing a mix of different file types on Windows 2000.
use strict; local *DIR; opendir(DIR, '.') or die "Failed to open: $!\n"; my $file; while (defined($file = readdir(DIR))) { print "$file: ", (stat($file))[7], "\n"; } closedir(DIR); .: 16384 ..: 8192 12810005141553.zip: 971956 12810005141553_log.txt: 228 12820005141551_log.txt: 228 200310271800.xml: 48819126 200310291515.xml: 612137 nasimage.zip: 41993313 newoutfits.zip: 412923 PDLnewitems_v2.txt: 1163863 plm_logo_82x27.gif: 1182 price.zip: 1686002 prod_summary.txt: 10587 reconcile.xls: 21956096 relation_summary.txt: 86904 rob_resume.doc: 26624 shipped_20031030.xls: 56832 uo.gif: 549

Replies are listed 'Best First'.
Re^2: no size with stat and lstat in windows
by Scarborough (Hermit) on Sep 20, 2004 at 15:38 UTC

    I'm running this code

    use strict; my $dir = "c:\\params"; opendir DIR, $dir or die $!; foreach my $file (readdir(DIR)){ unless(-d $file){ print $file; my @stats = lstat ($file); print "\t\$stat = $stats[7]\n"; } }

    And get this

    AMRO $stat = DATE CATEGORY $stat = NEON $stat = PARAMIN.pm $stat = 1137 SMSL $stat = SMSREPSMEMIDCTOTS10.TXT $stat = SMSREPSMEMIDCTOTS11.TXT $stat = SMSREPSMEMIDCTOTS12.TXT $stat = SMSREPSMEMIDCTOTS13.TXT $stat = SMSREPSMEMIDCTOTS14.TXT $stat = tp1.pl $stat = 247

    Which has 2 errors no stats for the TXT files and NEON and SMSL are directories but . and .. are filtered out.

    Anyone seem this at all
      It's always good to include (a small bit of) the code you are having a problem with. Thus we can see you missed a bit in the description of readdir(). readdir() only gives you the next name out of the directory, which is thus only the filename, and not including the path to the directory. In steves example notice that he used directory '.' so there wasn't a path to worry about.

      Anyway, check this modified version of your code:

      use File::Spec; my $dir = "c:\\Perl"; opendir DIR, $dir or die $!; foreach my $file (readdir(DIR)){ my $path_to_file = File::Spec->catfile( $dir, $file ); printf " I see file '%s' path '%s'\n", $file, $path_to_file; next unless -e $path_to_file; unless(-d $path_to_file){ print $path_to_file; my @stats = lstat ($path_to_file); print "\t\$stat = $stats[7]\n"; } }
      Note that the full path to the file to use with -d , -e , or lstat() is the combination of the directory path plus the filename returned from readdir().

      I used the File::Spec module to combine these because I'd rather let it worry about combining directory paths and filenames and getting the '/' or '\' separators correct.

        Thanks to both of you for your help I see the problem now and have reworked the code accordingly.