ocamlmkdirsys

Create directory when it does not exist


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!


Solution

  • 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 0o777 for the sake of full permissions, but in practice this is probably a bad idea.

    let full_permission = 0o777 in
    try 
      if not (Sys.is_directory "vegetables") then 
        Sys.mkdir "vegetabels" full_permission
    with Sys_error _ ->
      Sys.mkdir "vegetabels" full_permission
    

    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.

    let full_permission = 0o777 in
    try
      Sys.mkdir "vegetabels" full_permission
    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.