2

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 2

7

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
2

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.

4
  • Is it possible to create a file right afterwards. I always get Sys_error "vegetables/apple.txt: Permission Denied". Only when I restart the program apple.txt is created. Already tried it with 777 - still not allowed
    – col.ulb
    Commented Jan 9, 2022 at 9:39
  • 1
    @col.ulb: Both in your original question and in this answer vegetables is spelt incorrectly. Make sure you always spell it the same way.
    – janneb
    Commented Jan 9, 2022 at 18:57
  • 1
    As a tiny nit, using mkdir and handling the error if it already exists avoids the time-of-check to time-of-use race. Perhaps it's not a concern for this particular application, but it's good hygiene to avoid it in general.
    – janneb
    Commented Jan 9, 2022 at 19:00
  • 1
    The constant above should be octal, not decimal: 0o777. Commented Aug 3, 2022 at 7:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.