ace007
ace007

Reputation: 577

read text file and concat lines

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

Answers (1)

gasche
gasche

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:

  1. Use the Buffer module that was precisely designed to accumulate strings
  2. Collect lines in a list of lines, and finally concatenate them all in one go with the efficient String.concat : string -> string list -> string function (documentation).
  3. Use an existing library that does that for you. For example, Batteries has the input_all function to get the whole content of an input channel into a file.

.

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

Related Questions