如何将给定文件的整个内容读入字符串?

Lav*_*air 3 ocaml

我的给定文件/path/file.txt包含例如以下内容:

你好,世界!
试着读我.

如何在代码中将整个内容读入单个字符串?
对于此特定示例,字符串应如下所示:

"Hello World!\nTry to read me."
Run Code Online (Sandbox Code Playgroud)

Ulu*_*aev 5

为了使下面的解决方案起作用,您需要Core通过open Core在使用以下任何代码的位置上方的任何行上书写来使用Jane Street 的图书馆。

In_channel.read_all "./input.txt"input.txt以单个字符串形式返回当前文件夹中的内容。

也有用:

  • In_channel.read_lines "./input.txt" 返回文件中的行列表

  • In_channel.fold_lines 允许“折叠”文件中的所有行。


Jef*_*eld 5

如果您不想使用Core,则以下内容使用内置Pervasives模块中的函数:

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
Run Code Online (Sandbox Code Playgroud)

  • 在具有 DOS (CRLF) 行结尾的 Windows 上,`really_input_string` 可能会引发 `End_of_file`,因为 `in_channel_length` 不会进行字符转换,但 `open_in` 会进行转换,并且预期的字符数将大于读取的字符数转换后。一种可能的解决方案是使用“open_in_bin”。 (3认同)