Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ocaml

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."
like image 966
Lavair Avatar asked Dec 18 '18 19:12

Lavair


1 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
like image 199
Jeffrey Scofield Avatar answered Nov 10 '22 01:11

Jeffrey Scofield