Input / Output & Files

⚠️ Not type-safe; never unmarshal untrusted data.

19.1 Console I/O

print_string "no newline"; print_newline ()
print_endline "with newline"
print_int 42; print_float 3.14; print_char 'x'
prerr_endline "to stderr"
let line = read_line ()         (* raises End_of_file *)
let n = read_int ()

19.2 Channels

(* Writing *)
let () =
  let oc = open_out "out.txt" in
  output_string oc "Hello\n";
  Printf.fprintf oc "%d\n" 42;
  close_out oc

(* Reading line by line *)
let read_lines path =
  let ic = open_in path in
  let rec loop acc =
    match input_line ic with
    | line -> loop (line :: acc)
    | exception End_of_file -> close_in ic; List.rev acc
  in
  loop []

19.3 Modern In_channel / Out_channel (4.14+)

let contents = In_channel.with_open_text "data.txt" In_channel.input_all
let lines = In_channel.with_open_text "data.txt" In_channel.input_lines   (* 5.1+ *)

let () =
  Out_channel.with_open_text "out.txt" (fun oc ->
    Out_channel.output_string oc "written safely\n")

In_channel.input_line ic       (* string option *)
Out_channel.with_open_bin, In_channel.with_open_bin

19.4 Binary files & seeking

let ic = open_in_bin "file.bin" in
let len = in_channel_length ic in
let data = really_input_string ic len in
seek_in ic 0; pos_in ic;
close_in ic

19.5 Marshal (binary serialization of OCaml values)

⚠️ Not type-safe; never unmarshal untrusted data.

let () = Out_channel.with_open_bin "data.bin" (fun oc -> Marshal.to_channel oc [1;2;3] [])
let (l : int list) = In_channel.with_open_bin "data.bin" Marshal.from_channel

19.6 Sys and Filename

Sys.argv                     (* command-line args array *)
Sys.getenv_opt "HOME"
Sys.file_exists "x.txt", Sys.is_directory "."
Sys.readdir "."              (* string array *)
Sys.remove "f", Sys.rename "a" "b"
Sys.command "ls -l"          (* run shell command, returns exit code *)
Sys.time ()                  (* processor time *)
Sys.os_type                  (* "Unix" | "Win32" | "Cygwin" *)
Filename.concat "dir" "file.txt"
Filename.basename, Filename.dirname, Filename.extension, Filename.remove_extension
Filename.temp_file "pre" ".tmp"
exit 0
at_exit (fun () -> print_endline "bye")