Take the 2-minute tour ×

I can use the following function to overwrite a text file:

let writeFile ~filename:fn s =
let oc = open_out fn in
    output_string oc s;
    close_out oc ;;

Howeve, i donot know how to append a line to a text file ?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

You could pass additional mode flag Open_append to open_out_gen function:

let _ =
    let oc = open_out_gen [Open_creat; Open_text; Open_append] 0o640 "a.txt" in
    output_string oc "append\n";
    close_out oc
share|improve this answer
Good idea. I wasn't sure what the semantics were, but it appears that Open_append just seeks to the end of the file for you. (I thought it might use Unix O_APPEND, which causes every write to append to the file, no matter where the file position is.) –  Jeffrey Scofield Nov 11 '11 at 9:01
Whoops, my test was wrong. Open_append does cause every write to append to the file. So you should use it carefully, only when that's what you really want to do. Regards, –  Jeffrey Scofield Nov 11 '11 at 9:03
@JeffreyScofield: you are right, the file can not be seeked if opened in append mode (same as fopen in c). –  barti_ddu Nov 11 '11 at 9:27
(Technically in c if you open in a+ mode, you can seek for reading, but writes still go to the end. There's no update mode in the OCaml pervasives, though.) –  Jeffrey Scofield Nov 11 '11 at 17:04

This is what I do:

let append_string path s =
    let chan = open_out_gen [Open_wronly; Open_creat] 0o666 path
    in let len = out_channel_length chan
        seek_out chan len;
        output_string chan s;
        close_out chan;
share|improve this answer

Your Answer


