Writing and reading a custom variable to a file in Ocaml

I am trying to write and then read a variable into a file. The variable is from the data type I created.

(If helps:

type sys = Line file * list of lines | Folder of the line * sys list ;;

)

How can i do this? I read about using fprintf, but why did I need to convert it somehow to a string first, right?

+6
source share
1 answer

If you are sure that 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 be interrupted whenever you try to read a value stored in a different version of sys (or if you change your version of OCaml between writing and reading).

If you need security, you can use an automatic serializer like sexplib (if you want to read the file you create) or biniou for efficient conversion.

+7
source

Source: https://habr.com/ru/post/911993/


All Articles