I'm trying to write and then read a variable to a file. The variable is from a data type created by me.
(If helps:
type sys = File of string * string list | Folder of string * sys list ;;
)
How can I do this? I've been reading about the use of fprintf, but for what I get it'd had to be converted somehow into a String first, right?
If you are sure your type will not change, you can use input_value
and output_value
from Pervasives.
let write_sys sys file =
let oc = open_out file in
output_value oc sys;
close_out oc
let read_sys file =
let ic = open_in file in
let sys : sys = input_value ic in
close_in ic;
sys
read_sys
will break whenever you will try to read value stored with an other version of sys
(or if you change your version of OCaml between writing and reading).
If you want safety, you can use automatic serializer such as sexplib (if you want to be able to read the file you are creating) or biniou for efficient conversion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With