Title here
Summary here
Here’s the translation of the Go code to OCaml, along with explanations in Markdown format suitable for Hugo:
Writing files in OCaml follows similar patterns to the ones we saw earlier for reading.
open Printf
(* Helper function to handle exceptions *)
let check_exn f x =
try f x with
| e -> failwith (Printexc.to_string e)
let () =
(* To start, here's how to dump a string (or just bytes) into a file. *)
let d1 = "hello\nocaml\n" in
check_exn (Sys.write_file "/tmp/dat1" d1) ();
(* For more granular writes, open a file for writing. *)
let oc = open_out "/tmp/dat2" in
(* It's idiomatic to use a try-finally block to ensure the file is closed *)
try
(* You can write strings as you'd expect. *)
let d2 = "some\n" in
output_string oc d2;
printf "wrote %d bytes\n" (String.length d2);
(* A write_string function is available in the Printf module. *)
let n3 = fprintf oc "writes\n" in
printf "wrote %d bytes\n" n3;
(* Flush writes to ensure they're written to the file. *)
flush oc;
(* OCaml provides buffered output channels. *)
let n4 = fprintf oc "buffered\n" in
printf "wrote %d bytes\n" n4;
(* Use flush to ensure all buffered operations have been applied. *)
flush oc;
finally
close_out oc
Try running the file-writing code.
$ ocaml writing_files.ml
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes
Then check the contents of the written files.
$ cat /tmp/dat1
hello
ocaml
$ cat /tmp/dat2
some
writes
buffered
Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin
and stdout
streams.