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

getting file sizes 1

Status
Not open for further replies.

tsp120

Programmer
May 21, 2003
52
US
Hi, I need to write a program to search through a directory, or a set of directories, and acquire the file sizes of all directories and files, then display them in a sorted order in Unix. I know how to navigate through directories and such but have no idea how to get the file sizes. Any help would be appreciated.

Thanks.
 
One easy way is to use stat() i.e.

( $dev, $ino, $mode, $nlink,
$uid, $gid, $rdev, $size,
$atime, $mtime, $ctime,
$blksize, $blocks ) = stat($filename)
or die "no $filename: $!";

Using the above, the size of the file is given by $size.

Very straightforward.
 
thanks, I think that will help. However I am very very new at Perl. After I call the stat function, do I just use the variable "$size" and populate it in an array or am I missing how the function works?
 
A very quick implementation:

Code:
#!/usr/contrib/bin/perl 
use File::Find;
my @fileinlist;  
my $firstdir='C:\temp';
chdir $firstdir or die "cannot chdir to $firstdir: $!";          # change to first directory                                 
find sub { $fileinlist [ $i++ ] = $File::Find::name }, '.'; 	 # obtain list of all files
foreach my $filename (@fileinlist) {
	( $dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks )= stat($filename) or die "no $filename: $!";
	print "$filename is $size\n";
}

Hope that helps.
 
this is working great, however when I specify a directory for $firstdir, it looks at all files even outside the directory. Am I doing something wrong?
 
Getting sizefile...


$sizefile= -s $file;
$sizefile = ($sizefile / 1048756);
if ($sizefile > 5) {
print "The file: $file is bigger than 5 MB.\n";
}


dmazzini
GSM System and Telecomm Consultant

 
tsp120 - must be related to the chdir or the point from which you are running the file-find. Post your code and we ought to be able to resolve it.
 
tony, turns out I was wrong. I just didn't realize how much junk I had in the directory I was using. Its working fine. I greatly appreciate the help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top