Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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))
        allFiles ~= entry;
    auto sorted = sort!((a, b) => a.size > b.size)(allFiles);
    auto filtered = filter!((a) => Clock.currTime() - a.timeLastModified >> 14.days)(sorted);
    foreach(file; filtered.take!...