O'Reilly logo

D Cookbook by Adam D. Ruppe

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Finding the largest files in a directory

Suppose you're out of disk space. A solution may be to delete old, large files from a directory. Let's write a D program to perform this task.

How to do it…

Execute the following steps to find the largest files in a directory:

  1. Use the std.file.dirEntries function to get a listing of all files.
  2. Define the DirEntry variable as an array.
  3. Sort the array by size in descending order by using std.algorithm and a lambda function.
  4. Filter out the newer files with std.algorithm.filter.
  5. Delete the top 10 files with the std.file.remove function.

The code is as follows:

void main() { import std.file, std.algorithm, std.datetime, std.range; DirEntry[] allFiles; foreach(DirEntry entry; dirEntries("target_directory", SpanMode.depth)) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required