Flux
Flux

Reputation: 10930

How to remove a non-empty directory with OCaml?

I tried to remove a directory using Sys.remove "mydir", but this results in an exception: Exception: Sys_error u"mydir: Is a directory"..

Next I looked at Unix.rmdir "mydir", but that did not work because the directory is not empty (it resulted in Exception: Unix.Unix_error (27, "rmdir", "mydir").

So I guess the only way to delete a non-empty directory is to get the list of files in the directory using Sys.readdir "mydir", then delete its contents recursively before finally deleting the empty directory using Unix.rmdir.

What is the idiomatic way of removing a non-empty directory using OCaml?

Upvotes: 0

Views: 751

Answers (1)

ivg
ivg

Reputation: 35260

You have to recursively remove its contents first, using Sys.remove and Sys.readdir, and, once it is empty, remove the directory itself, e.g.,

let rec rmrf path = match Sys.is_directory path with
  | true ->
    Sys.readdir path |>
    Array.iter (fun name -> rmrf (Filename.concat path name));
    Unix.rmdir path
  | false -> Sys.remove path

Alternatively, you can use the OCaml Fileutils library, which provides POSIX compliant file utilities, namely the rm function, that could recursively (and portably) delete the whole directory, e.g.,

 FileUtil.rm ~recurse:true [dir]

Upvotes: 2

Related Questions