I have been trying to figure out how to create a filesystem file making sure to automatically create intermediate directories. The following snippet does not seem to work at all:
I keep getting the Exception: Sys_error "/some/dir/more/dirs/basepath.ext: No such file or directory". error. Is there a way to ensure the intermediate directories /more/dirs/ get auto created if /some/dir/ already exists while requesting for /some/dir/more/dirs/basepath.ext: to be created?
I think you will need to do this ‘manually’ for each directory. Fortunately, there are helper functions in the Sys module that can help: eg file_exists, is_directory, and mkdir. I recommend a function signature like this:
val write_to : ~path:string list -> string -> unit
To be called like:
write_to ~path:["some"; "dir"; "more"; "dirs"; "basepath.ext"] value
let rec create_parent_dir fn =
let parent_dir = Filename.dirname fn in
if not (Sys.file_exists parent_dir) then begin
create_parent_dir parent_dir;
Sys.mkdir parent_dir
end
let openfile fn =
create_parent_dir fn;
Out_channel.with_open_gen ... fn ...