2013-04-06 59 views
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 

這只是給我一個語法錯誤。

我該怎麼做?

+0

例如這裏你似乎也不在乎你得到答案。如果你想讓人們花時間回答你的問題,你需要付出一些努力,否則他們不會。 – Thomas 2013-04-07 10:54:12

回答

0

我看到的唯一語法錯誤是在let string = Buffer.contents buf之後缺少in

Buffer.add_channel的作用是將給定通道中給定數量的字符加到緩衝區中。除非您的文件"myfile.txt"特別大,否則打印時緩衝區將爲空。

事實上,在我的系統(一個64位系統)中,max_int非常大,所以Buffer.add_channel甚至不會嘗試讀取那麼多的數據。它引發了一個Invalid_argument異常。

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