无法停止文件读取过程

时间:2013-04-06 17:50:01

标签: ocaml

当我点击“停止”的文本行时,我正在尝试退出循环,将文件内容读入列表。这是我的代码:

let f_in = "file.text"
let lines = ref [];;

  let chan = open_in f_in in
  try
    while true do

      let line = input_line chan in
      if line = "stop" then raise End_of_file;
      lines := input_line chan :: !lines

    done
  with End_of_file -> close_in chan

问题是它正在读取1个额外的行,并且它不会读取文本中包含“停止”一词的行。一个例子就是这种文件:

aaa
bbb stop
ccc stop
ddd
eee
stop
fff

现在我的代码应该打印所有这些行,并停止阅读单独使用“停止”一词的行。有人能解决这个问题吗感谢。

1 个答案:

答案 0 :(得分:0)

input_line替换第二个line会产生您想要的结果。

let f_in = "file.text"
let lines = ref [];;

let chan = open_in f_in in
  try
    while true do

      let line = input_line chan in
      if line = "stop" then raise End_of_file;
      lines := !lines @ [ line ]

    done
  with End_of_file -> close_in can

lines中存储的结果是:

["aaa"; "bbb stop"; "ccc stop"; "ddd"; "eee"]