How do I read the entire content of a given file into a string?

For the solution below to work, you need to use Core library by Jane Street by writing open Core on any line above the place where you use any of the code below.

In_channel.read_all "./input.txt" returns you the content of input.txt in the current folder in a single string.

Also useful:

  • In_channel.read_lines "./input.txt" returns a list of lines in the file

  • In_channel.fold_lines allows to "fold over" all lines in the file.


If you don't want to use Core, the following works with functions from the built-in Pervasives module:

let read_whole_file filename =
    let ch = open_in filename in
    let s = really_input_string ch (in_channel_length ch) in
    close_in ch;
    s

Tags:

Ocaml