Search code examples
ocaml

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


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
    Std.input_list (chan)

Solution

  • Editor's note: this answer was good for previous versions of OCaml; with version 4.14.0 and above, please consider these answers instead: https://stackoverflow.com/a/73019499/ and https://stackoverflow.com/a/77625257/

    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