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

Viewed 3624

My given file /path/file.txt contains for example the following:

Hello World!
Try to read me.

How can I read the entire content into one single string inside my code?
For this specific example, the string should look like this:

"Hello World!\nTry to read me."
2 Answers

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

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.

Related