我想使用Ocamllex/Ocamlyacc构建一个编译器,我想创建一个主程序来结合我的OcamlParser和OcamlLexer。问题是,我知道如何在命令行中使用如下代码的输入来实现:
let _ =
try
let lexbuf = Lexing.from_channel stdin in
while true do
let result = Parser.main Lexer.token lexbuf in
print_int result; print_newline(); flush stdout
done
with Lexer.Eof ->
exit 0
但是如果我想使用一个文件作为输入,我该怎么做?我尝试这样做:
let file ="add.txt"
let _ =
let ic = open_in file in
try
let lexbuf = Lexing.from_channel file in
while true do
let result = Parser.main Lexer.token lexbuf in
print_int result; print_newline(); flush stdout
done
with Lexer.Eof ->
exit 0
但它并没有真正起作用。
下面的代码适合我。在你的版本中,你有一些语法错误。
let _ =
let file ="add.txt" in
let i = open_in file in
try
let lexbuf = Lexing.from_channel i in
while true do
let result = Parser.main Lexer.token lexbuf in
print_int result; print_newline(); flush stdout
done
with Lexer.Eof ->
exit 0
将1+2
放入"add.txt"中得到3
。