How to implement “appendFile” function?

。_饼干妹妹 提交于 2020-07-03 04:22:13

问题


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 ?


回答1:


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



回答2:


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
    in
        begin
        seek_out chan len;
        output_string chan s;
        close_out chan;
        end


来源:https://stackoverflow.com/questions/8090490/how-to-implement-appendfile-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!