0

我想打印文件的内容。我尝试使用字符串缓冲区:

let ch = open_in "myfile.txt" in
let buf = Buffer.create 1024 in
(try Buffer.add_channel buf ch max_int with _ -> ());
close_in ch;

let string = Buffer.contents buf
print_endline string

这只是给了我一个语法错误。

我怎样才能做到这一点?

4

2 回答 2

2

您需要提供正确的通道长度:

let ic = open_in "foo" in
let len = in_channel_length ic in
let buf = Buffer.create len in
Buffer.add_channel bif ic len;
let str = Buffer.contents b in
print_endline str
于 2013-04-06T13:05:26.177 回答
0

The only syntax error I see is a missing in after let string = Buffer.contents buf.

The purpose of Buffer.add_channel is to add exactly the given number of characters from the given channel to the buffer. Unless your file "myfile.txt" is exceptionally large, the buffer will be empty when you print it out.

In fact on my system (a 64-bit system), max_int is so large that Buffer.add_channel doesn't even try to read that much data. It raises an Invalid_argument exception.

于 2013-04-06T03:20:07.917 回答