Create directory when it does not exist

Viewed 228

I want to create a new directory if it doesn't exist already. Tried several things, sadly I didn't find something in the Sys Library.

The nearest solution I got was: if not (Sys.is_directory "vegetables") then Sys.mkdir "vegetabels"

Which obviously doesn't work since an exception is thrown. Thank you!

2 Answers

You missed Sys.file_exists (directories are considered to be files in unix-like systems):

let create_newdir path perm =
  if not (Sys.file_exists path) then Sys.mkdir path perm

You can check using file_exists, which is the best approach, but it's also helpful to know how to handle exceptions.

Please note mkdir requires a permissions value. I'll use 777 for the sake of full permissions, but in practice this is probably a bad idea.

try 
  if not (Sys.is_directory "vegetables") then 
    Sys.mkdir "vegetabels" 777
with Sys_error _ ->
  Sys.mkdir "vegetabels" 777

Alternatively, Sys.mkdir raises an exception if the directory or file already exists, so we can try to create the directory, and handle that exception by doing nothing.

try
  Sys.mkdir "vegetabels" 777
with Sys_error _ -> ()

Note: when you use exception handling, it's not an excuse to forget about type-checking. The type of the body of your try needs to have the same type as any with clauses. Since Sys.mkdir returns unit if successful, the exception handling clause needs to do the same.

Related