使用標準函式庫讀寫文字檔
任務
檔案系統 / 讀寫文字檔
未使用任何套件
本食譜僅使用 OCaml 標準函式庫。程式碼
In_channel.with_open_text
開啟指定路徑的檔案通道。input_all
讀取輸入通道的所有資料,並將其作為字串返回。這些函式可能會拋出 Sys_error
例外。
let read_text_from_file filename =
try
In_channel.with_open_text
filename
In_channel.input_all
with Sys_error msg ->
failwith ("Failed to read from file: " ^ msg)
Out_channel.with_open_text
安全地開啟檔案,將文字寫入其中,並自動關閉它。
let write_text_to_file filename text =
Out_channel.with_open_text
filename
(fun out_channel ->
Out_channel.output_string out_channel text)