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:
Use the
std.file.dirEntries
function to get a listing of all files.Define the
DirEntry
variable as an array.Sort the array by size in descending order by using
std.algorithm
and a lambda function.Filter out the newer files with
std.algorithm.filter
.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!...