Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writting and reading a custom variable to a file in Ocaml

Tags:

ocaml

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?

like image 923
EBM Avatar asked Mar 29 '12 22:03

EBM


1 Answers

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.

like image 126
Thomas Avatar answered Oct 06 '22 02:10

Thomas