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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help traversing a filesystem 3

Status
Not open for further replies.

gregmosu

Programmer
Jul 8, 2002
117
US
I am trying to write a script that will traverse a file system from a given starting point. I had no problem doing this in java, but converting it to perl wasnt as easy. So far, the script explores all the directies sitting in the relative root dir(whatever starting point i give it)... and prints the files in those directories, but doesnt explore any of their subdirectories. Here is what I have so far....

#!/usr/bin/perl -s

my $start_point=".";

&Traverse($start_point);

sub Traverse{
my ($workdir) = shift;
opendir(DIR, $workdir) or die "Unable to open $workdir:$!\n";
my @dirarray = readdir(DIR) or die "Unable to read $workdir:$!\n";
&PrintFileInfo($workdir);
foreach my $name (@dirarray){
next if $name eq ".";
next if $name eq "..";
if(-d $name){
&Traverse($name);
} else {
&PrintFileInfo($name);
}
}
}

sub PrintFileInfo{
my ($file) = shift;
if(-d $file){
print "DIRECTORY $file\n";
} else {
print "\tFILE $file\n";
}
}



Thanks,
Greg
 
The problem is that you need the full pathname to the file. Here's the code with changes in red
my $start_point=".";

&Traverse($start_point);

sub Traverse{
my ($workdir) = shift;
opendir(DIR, $workdir) or die "Unable to open $workdir:$!\n";
my @dirarray = readdir(DIR) or die "Unable to read $workdir:$!\n";
&PrintFileInfo($workdir);
foreach my $name (@dirarray){
next if $name eq ".";
next if $name eq "..";
$fullname = $workdir . "\\" . $name;
if (-d $fullname){
&Traverse($fullname);
} else {
&PrintFileInfo($fullname);
}

}
}

sub PrintFileInfo{
my ($file) = shift;
if(-d $file){
print "DIRECTORY $file\n";
} else {
print "\tFILE $file\n";
}
}
 
Or, as icrf said, use File::Find



use File::Find;
find (\&wanted, "start point goes here");
sub wanted {
-f and push @array,$File::Find::name;
}
foreach (@array) {
print ("$_\n");
}


That is all there is too it.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top