Home > Concepts and Solutions > Perl on Windows > Getting Windows File Attributes
Getting Windows File Attributes
User Rating: / 0
PoorBest 
Perl on Windows
Written by Philip L Yuson   
Who is this for
This article is for programmers who need to get file attributes under a Windows operating System What you need to know
  • Basic Windows commands

  • Basic Perl programming

Introduction
Sometime ago, I needed to compare two directories and compare the timestamp of the files in these directories. This was fairly easy. However, the difficult part was to recurse to files within subdirectories.

On a Linux/Unix machine, you can do a stat in Perl and check for the directory bit in the file mode item returned from stat.

But this is Windows so stat does not return any information on whether the name is a directory or a file. What did I do?

Option 1: The Quick Way
I have to confess that I cheated. I did this:

open (POOL, "dir $pool |") || die "Cannot open $pool\n";
while () {

if ($pool =~ m/<DIR>/gi) { processDir() }

}



This is the simplest way because it uses the DIR command in DOS and determines if the name is a directory or not based on the string <DIR> that is displayed by the command.

Option 2: The Cleaner Way

The cleaner way is to use the Win32::File module. This module has two methods: GetAttributes and SetAttributes. It also has several constants that you can use to determine the attributes of a given file.

The format of the commands are:

GetAttributes($filename, $resultattr);

SetAttributes($filename, $attrtoset);



Each bit of the resulting byte ($resultattr) from GetAttributes identifies an attribute. To determine the attribute of a file, you need to check if the bit is a 1. You can use these constants to simplify things for you.

ARCHIVE COMPRESSED DIRECTORY HIDDEN NORMAL OFFLINE READONLY SYSTEM TEMPORARY

This is a sample routine to show how this works:

#!perl -w

use Win32::File;


my ($pool) = @ARGV;

my ($file, $attr);


opendir (DIR, $pool);

while ($file = readdir(DIR)) {

print "Name: $file ";

Win32::File::GetAttributes("$pool/$file", $attr);

if ($attr & DIRECTORY) { print "Directory " }

print "Attr: $attr\n";

}



You will need to specify the Win32::File module. We then get the directory to be scanned from the parameter passed to the script.

We then defined the variables to be used within the script.


Next step is to open the directory and read all the contents of the directory. This is done through the while ($file = readdir(DIR)) statement. Once you have the name in the directory, you can GetAttributes it and check for the type of the file.


For more information on Win32::File and all Win32 modules, go to the Roth Consulting website.



 
Copyright: © 2017 Philip Yuson