From b0b768b60ab3e9eec1b4c334cebf9d9e3f1a08ce Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Sat, 20 Feb 2016 23:36:48 +0100 Subject: [PATCH] add `CCIO.File.{read,write,append}` for quickly handling files --- src/core/CCIO.ml | 16 ++++++++++++++++ src/core/CCIO.mli | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/core/CCIO.ml b/src/core/CCIO.ml index 6eaaa6c9..5de7ed60 100644 --- a/src/core/CCIO.ml +++ b/src/core/CCIO.ml @@ -260,6 +260,22 @@ module File = struct with exn -> `Error (Printexc.to_string exn) + let read_exn f = with_in f (read_all_ ~op:Ret_string ~size:4096) + + let read f = try `Ok (read_exn f) with e -> `Error (Printexc.to_string e) + + let append_exn f x = + with_out ~flags:[Open_append; Open_creat; Open_text] f + (fun oc -> output_string oc x; flush oc) + + let append f x = try `Ok (append_exn f x) with e -> `Error (Printexc.to_string e) + + let write_exn f x = + with_out f + (fun oc -> output_string oc x; flush oc) + + let write f x = try `Ok (write_exn f x) with e -> `Error (Printexc.to_string e) + let remove_noerr f = try Sys.remove f with _ -> () let read_dir_base d = diff --git a/src/core/CCIO.mli b/src/core/CCIO.mli index a29c0af6..b112b111 100644 --- a/src/core/CCIO.mli +++ b/src/core/CCIO.mli @@ -162,6 +162,30 @@ module File : sig @param recurse if true (default [false]), sub-directories are also explored *) + val read_exn : t -> string + (** Read the content of the given file, or raises some exception + @since NEXT_RELEASE *) + + val read : t -> string or_error + (** Read the content of the given file + @since NEXT_RELEASE *) + + val append_exn : t -> string -> unit + (** Append the given string into the given file, possibly raising + @since NEXT_RELEASE *) + + val append : t -> string -> unit or_error + (** Append the given string into the given file + @since NEXT_RELEASE *) + + val write_exn : t -> string -> unit + (** Write the given string into the given file, possibly raising + @since NEXT_RELEASE *) + + val write : t -> string -> unit or_error + (** Write the given string into the given file + @since NEXT_RELEASE *) + type walk_item = [`File | `Dir] * t val walk : t -> walk_item gen