Reputation: 577
I have posted a few questions about file IO i'm just trying to find the right one for my needs, I have found and I also googled allot so I guess my final file IO questions is (you will see some pseudo code here):
let ic = open_in "myfile.txt" in
try
while true do
let line = input_line ic in
line += "\n" + line
done
with End_of_file -> close_in ic;
print_endline line;;
I have tried String.concat "\n" (line; line) clearly it's invalid but im unsure in this situation how I would use String.concat method.
Upvotes: 1
Views: 665
Reputation: 31459
String concatenation is inadequate in this situation because str1 ^ str2
takes time and memory linear in the sum of the sizes, so iterated concatenation would exhibit quadratic behavior -- you want to avoid that.
There are several solutions to your problem:
String.concat : string -> string list -> string
function (documentation)..
let read_file file =
let ic = open_in file in
let buf = Buffer.create (in_channel_length ic) in
try
while true do
let line = input_line ic in
Buffer.add_string buf line;
Buffer.add_char buf '\n';
done; assert false
with End_of_file ->
Buffer.contents buf
;;
let read_file file =
let ic = open_in file in
let lines = ref [] in
try
while true do
let line = input_line ic in
lines := line :: !lines
done; assert false
with End_of_file ->
String.concat "\n" !lines
let test = read_file "blah.ml"
Upvotes: 4