How do I read in lines from a text file in OCaml?

后端 未结 7 962
心在旅途
心在旅途 2020-12-31 02:18

This is what I have so far. Isn\'t this all that you need? I keep getting the error \"Error: Unbound module Std\"

let r file =
    let chan = open_in file in         


        
7条回答
  •  失恋的感觉
    2020-12-31 03:05

    An imperative solution using just the standard library:

    let read_file filename = 
    let lines = ref [] in
    let chan = open_in filename in
    try
      while true; do
        lines := input_line chan :: !lines
      done; !lines
    with End_of_file ->
      close_in chan;
      List.rev !lines ;;
    

    If you have the Batteries-included library you could read a file into an Enum.t and iterate over it as follows:

    let filelines = File.lines_of filename in
    Enum.iter ( fun line -> (*Do something with line here*) ) filelines
    

提交回复
热议问题