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

Counting files with readdir

Status
Not open for further replies.

nook6

Programmer
Dec 18, 2002
24
0
0
GB
Hi

Hopefully a simple one here.

How can i count how many files are in a directory.
I want to get a reply of lets say 4 files in such and such directory.

Nook6
 
Code:
$directory = '.';
opendir DIR, $directory;
@fileList = readdir DIR;
closedir DIR;

print scalar(@filelist);
I just open the current working directory, can change that to anything. This directory listing also includes "." and ".." (current directory and parent directory), so you'll probably want to filter those out of your calculations. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Hi

ICRF sorry but this doesnt seem to work i keep getting 0
And the path is correct and the folder has three files in it.

Nook6
 
Sorry about that. Capitalization problem. I read into @fileList and get the length of @filelist (note the difference in l/L case). A smart fella starts every script with "use strict;" and is forced to declare everything first with 'my'.
Code:
use strict;
my $directory = '.';
opendir DIR, $directory;
my @fileList = readdir DIR;
closedir DIR;
print join("\n",@fileList)."\nFiles in list: ".scalar(@fileList)."\n";
----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Hi

ICRF Im still having problems heres the code im using

$directory = "$config{'userpage'}$form{'ALIAS'}/";
opendir DIR, $directory;
@fileList = readdir DIR;
closedir DIR;
print join("\n",@fileList)."\nFiles in list: ".scalar(@fileList)."\n";


This is the result im getting

. .. index.html page1.html page2.html Files in list: 5

As you can see it is listing three files ( which is correct)But its saying 5 ??

Nook6
 
Well, the directory listing includes the current directory '.' and the parent directory '..' So if all you're after is a file count, you could probable just subtract two. If you're doing something with the files, you might want to remove those two before processing.

Might want to add a bit of error checking to the open, in case of bad naming or permissions.

Code:
opendir DIR, $directory;

could be

Code:
opendir DIR, $directory or die "Cannot open directory $directory: $!";
----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top