I've run into a strange problem using Core.In_channel
library. Here's a piece of code meant to open a file in the user's home directory
open Core.Std
In_channel.with_file "~/.todo_list" ~f:(fun in_c ->
(* Do something here... *)
)
However, when running this, here is what I get:
Exception: (Sys_error "~/.todo_list: No such file or directory").
I am absolutely sure that ~/.todo_list
exists, but I suspect that the filename is misinterpreted by OCaml.
What am I missing here?
As others have said, the expansion of ~
is done by the shell, not by the underlying system. No shell is involved in your call to with_file
so the string is interpreted literally as a file name.
If the code is running on behalf of a user who has logged in, the home directory is available as the value of the environment variable HOME
.
# Unix.getenv "HOME";;
- : string = "/Users/username"
Otherwise you will need to extract the home directory from the user database.
# let open Unix in (getpwnam "username").pw_dir;;
- : string = "/Users/username"