如何使用printf将字符串列表输出到文件中



我的目标是编写一个函数来读取open_out的字符串列表persons并将其存储在文件filename中我尝试用List来遍历它。fold_left和使用printf,但它不工作。

let write_list filename persons =
let file = open_out filename in 
let write_person p =
let rec ite_pres aux acc = List.fold_left (Printf.fprintf file "%sn" filename )
List.iter write_person persons;
close_out 

由于您想按文件打印一行List.iter就足够了:

let chan = 
List.iter (Printf.fprintf chan "%sn") persons

对于OCaml 4.14及以后的版本,你也可以使用with_open_text,它可以自己打开和关闭文件通道:

let write_list filename persons =
Out_channel.with_open_text filename (fun chan ->
List.iter (Printf.fprintf chan "%sn") persons
)

,

如果您想要做的只是将string list写入文件,每行一个元素,则不需要与折叠甚至Printf模块混淆。例如:

(* Like print_endline but for arbitrary output channels *)
let output_endline chan s = output_string chan s; output_char chan 'n'
(* Open a file and call f with the output channel as its argument.
* Note: Available as Out_channel.with_open_text in Ocaml 4.14 and newer *)
let with_open_text filename f =
let chan = open_out filename in
try
f chan; close_out chan
with x -> close_out chan; raise x
let print_list_to_file filename slst =
with_open_text filename (function chan -> List.iter (output_endline chan) slst)
let _ = print_list_to_file "output.txt" ["a";"b";"c"]

这定义了两个方便的函数,并使用List.iter来打印列表。

相关内容

  • 没有找到相关文章

最新更新