File_Utilities module

delete_directory_tree

procedure · 1 overloadsince 0.31.0Source

Deletes the folder path and everything in it. Returns whether the folder is gone.

File.delete_directory only removes an empty folder; this walks down first and removes the files, then the folders, deepest first. A link is deleted as a link and never followed, so what it points to is left alone, also when path itself is a link to a folder. false for a missing path, a path that is a file, or one with a NUL byte in it. If something cannot be removed (no permission, a read-only file on Windows), the rest is still tried and the answer is false, so a failure may leave part of the tree behind.

ExampleOpen in playground ↗
#import "Extensions/Environment";
#import "File";
base := environment_variable("TMPDIR");
if base == "" base = environment_variable("TEMP");
if base == "" base = "/tmp";
root := tprint("%/jai-doc-delete-tree", base);

assert(make_directory_if_it_does_not_exist(tprint("%/a/b", root), recursive = true));
assert(write_entire_file(tprint("%/a/b/leaf", root), "x"));
assert(!delete_directory(root)); // not empty

assert(delete_directory_tree(root));
assert(!file_exists(root));
assert(!delete_directory_tree(root)); // already gone
delete_directory_tree :: (path: string) -> bool

Deletes the folder path and everything in it. Returns whether the folder is gone.

File.delete_directory only removes an empty folder; this walks down first and removes the files, then the folders, deepest first. A link is deleted as a link and never followed, so what it points to is left alone, also when path itself is a link to a folder. false for a missing path, a path that is a file, or one with a NUL byte in it. If something cannot be removed (no permission, a read-only file on Windows), the rest is still tried and the answer is false, so a failure may leave part of the tree behind.

Parameters

path: string

Returns

bool
ExampleOpen in playground ↗
#import "Extensions/Environment";
#import "File";
base := environment_variable("TMPDIR");
if base == "" base = environment_variable("TEMP");
if base == "" base = "/tmp";
root := tprint("%/jai-doc-delete-tree", base);

assert(make_directory_if_it_does_not_exist(tprint("%/a/b", root), recursive = true));
assert(write_entire_file(tprint("%/a/b/leaf", root), "x"));
assert(!delete_directory(root)); // not empty

assert(delete_directory_tree(root));
assert(!file_exists(root));
assert(!delete_directory_tree(root)); // already gone