Finding the Largest File in a Directory

Here’s an easy way to find the largest file in a directory.

First, open the directory to read the list of file names in it.

  opendir DIR, $directory
      or die "Error reading $directory: $!\n";

Then, read the file names and sort according to size.

  my @sorted =
      sort {-s "$directory/$a" <=> -s "$directory/$b"}
	 readdir(DIR);

Finally, close the directory.

  closedir DIR;

Now you can print the name of the largest file.

  print "Largest file in $directory is $sorted[-1].\n";

Variations:

  • To get the oldest file, use -M instead of -s.
  • To get the smallest file, or the newest file, swap $a and $b.

Leave a Reply