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

后端 未结 7 988
心在旅途
心在旅途 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:02

    Another style to read lines from a file using Scanf "string indiciation" and zero-width character. It is like traditional imperative style.

    open Scanf 
    open Printf
    
    (* little helper functions *)
    let id x = x 
    let const x = fun _ -> x
    let read_line file = fscanf file "%s@\n" id 
    let is_eof file = try fscanf file "%0c" (const false) with End_of_file -> true
    
    let _ = 
      let file = open_in "/path/to/file" in 
    
      while not (is_eof file) do 
        let s = read_line file in
        (* do something with s *) 
        printf "%s\n" s 
      done;
    
      close_in file
    

    NOTE:

    1. read_line ignore one trailing \n, so if the last character of your file is \n, it may seems like you have missed the last empty line.
    2. when using of Scanf, due to bufferization, do not mix other low level reading on the same channel, otherwise it will result in strange behaviour.

提交回复
热议问题