Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 40 ยท Imperative Features and Exceptions

Input, Output and Formatting: Printf, Scanf and Files

Read and write data in OCaml. Print with Printf and Format, read stdin and files with channels, parse with Scanf, handle command-line arguments and format values safely at compile time.

Programs need to talk to the outside world: print results, read what users type, open files, take command-line arguments. OCaml's input and output is built on channels (in_channel and out_channel) and on a type-checked formatting system, Printf, that catches mismatched format strings at compile time.

OCaml is not available in the site's code runners, so ocaml blocks are read-only and show output only where it is certain. The Python stand-ins repeat the logic on in-memory text.

Printing

OCAML
let () =
  print_string "no newline";
  print_newline ();
  print_endline "with newline";
  print_int 42;
  print_char '\n';
  prerr_endline "this goes to stderr"

print_endline appends a newline and flushes. stdout is buffered, so output may appear late if the program crashes. Call flush stdout (or use print_endline) when it matters.

Printf: typed formatting

OCAML
let () =
  Printf.printf "%s is %d years old\n" "Ada" 36;
  Printf.printf "pi is about %.3f\n" 3.14159265;
  Printf.printf "|%5d|%-5d|%05d|\n" 42 42 42;
  Printf.printf "%x %o %b %c %S\n" 255 8 true 'z' "quoted"
(* Ada is 36 years old
   pi is about 3.142
   |   42|42   |00042|
   ff 10 true z "quoted" *)

Common directives:

Directive Meaning
%d, %i int
%f, %.2f, %e, %g float
%s string
%S string with quotes and escapes
%c char
%b bool
%x, %X, %o int in hex, octal
%a custom printer ((out_channel -> 'a -> unit) plus value)
%% a literal percent sign

The key point: the format string is a typed value. Printf.printf "%d\n" "oops" does not compile, and Printf.printf "%s %s\n" "one" has type string -> unit, a partially applied function waiting for the second argument. There is no run-time format error, and no missing-argument crash as in C.

To build a string instead of printing, use Printf.sprintf. To write to a channel use Printf.fprintf oc .... To print to a buffer use Printf.bprintf.

Format: pretty printing

Format adds boxes and break hints, so structured output wraps sensibly:

OCAML
let pp_list ppf xs =
  Format.fprintf ppf "[@[%a@]]"
    (Format.pp_print_list ~pp_sep:(fun ppf () -> Format.fprintf ppf ";@ ") Format.pp_print_int)
    xs

let () = Format.printf "%a@." pp_list [ 1; 2; 3 ]
(* prints: [1; 2; 3] *)

@[ ... @] opens and closes a box, @ is a breakable space, @. flushes with a newline. Use Format when you print trees, expressions or anything that must be re-indented to fit a line width; you will see it again in the JSON project.

Reading from standard input

OCAML
let () =
  print_string "name? ";
  flush stdout;
  let name = input_line stdin in
  Printf.printf "hi %s\n" name

input_line raises End_of_file when input runs out, which is the normal way to end a loop:

OCAML
let read_lines () =
  let rec go acc =
    match input_line stdin with
    | line -> go (line :: acc)
    | exception End_of_file -> List.rev acc
  in
  go []

Files

OCAML
let write_file path lines =
  let oc = open_out path in
  List.iter (fun l -> output_string oc (l ^ "\n")) lines;
  close_out oc

let read_all path =
  let ic = open_in path in
  let n = in_channel_length ic in
  let s = really_input_string ic n in
  close_in ic;
  s

If the body raises, the channel stays open. Use Fun.protect (exceptions) or the safer helpers added in OCaml 4.14:

OCAML
let content = In_channel.with_open_text "notes.txt" In_channel.input_all
let () = Out_channel.with_open_text "out.txt" (fun oc -> Out_channel.output_string oc "hello\n")

open_in_bin and open_out_bin avoid newline translation on Windows. open_out_gen [Open_append; Open_creat] 0o644 path appends.

Scanf: reading formatted input

OCAML
let () =
  let a, b = Scanf.sscanf "12 apples" "%d %s" (fun n w -> (n, w)) in
  Printf.printf "%d of %s\n" a b
(* prints: 12 of apples *)

Scanf.sscanf parses from a string, Scanf.scanf from stdin. Note the space before a directive in format strings such as " %d": it skips whitespace, which avoids newline problems when reading several numbers. For serious parsing, hand-written parsers or a parser library are more robust than Scanf.

Command-line arguments

OCAML
let () =
  let args = Array.to_list Sys.argv in
  match args with
  | _prog :: file :: _ -> Printf.printf "file: %s\n" file
  | _ -> prerr_endline "usage: prog FILE"; exit 2

Sys.argv.(0) is the program name. For flags and help text, the standard Arg module or the cmdliner library parse options for you. exit n ends the program with status n.

Strings and conversion helpers

OCAML
String.split_on_char ',' "a,b,c"        (* ["a"; "b"; "c"] *)
String.concat ", " [ "x"; "y" ]          (* "x, y" *)
String.trim "  hi  "                     (* "hi" *)
int_of_string_opt "42"                   (* Some 42 *)
float_of_string "3.5"                    (* 3.5 *)
string_of_float 2.0                      (* "2." โ€” note the trailing dot *)

OCaml prints float 2.0 as 2.. Use Printf.sprintf "%.1f" for stable output.

Stand-in: parsing lines from text

Python Stand-in: read lines, split, convert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The int(age) call plays the role of int_of_string_opt. In OCaml the failure would be an option you must match.

Common mistakes

  • Forgetting to flush before reading input, so the prompt appears late.
  • Leaking channels when an exception skips close_in.
  • Reading a number with scanf "%d" and leaving the newline behind. Use " %d".
  • Passing arguments to printf in the wrong order. The compiler catches type mismatches, but two strings can be swapped silently.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type does Printf.printf "%s %d\n" have?

    The directives determine the argument types, in order.
  2. 2. Which function builds a string with formatting instead of printing?

    sprintf returns the formatted string.
  3. 3. How is the end of standard input usually detected?

    Reading past the end raises End_of_file, which loops catch.
  4. 4. Why use In_channel.with_open_text?

    The with_ helpers wrap the open/close pair so channels are not leaked.

Summary

  • Output uses print_*, Printf (typed format strings) and Format (pretty printing with boxes).
  • Input and files use channels; end of input raises End_of_file. Prefer with_open_* helpers.
  • Scanf parses simple formatted text. Use Sys.argv or Arg for command-line input.
  • OCaml checks format strings at compile time, so mismatches cannot happen at run time.

Next: Dune and opam: Building and Managing Projects