From: Jonathan Knowles Date: Fri, 20 Nov 2009 14:22:16 +0000 (+0000) Subject: Adds functions "file_lines_{fold,iter}" to the Unixext module. These functions implem... X-Git-Url: http://xenbits.xensource.com/gitweb?a=commitdiff_plain;h=944272fb81b500bc9d8d715a57230cb3026e09d6;p=xcp%2Fxen-api-libs.git Adds functions "file_lines_{fold,iter}" to the Unixext module. These functions implement the standard "fold" and "iter" functions for all the lines in a file. Signed-off-by: Jonathan Knowles --- diff --git a/stdext/unixext.ml b/stdext/unixext.ml index ae0df74..e1a3734 100644 --- a/stdext/unixext.ml +++ b/stdext/unixext.ml @@ -85,18 +85,31 @@ let daemonize () = end | _ -> exit 0 -(** Run a function over every line in a file *) -let readfile_line fn fname = - let fin = open_in fname in +let file_lines_fold f start file_path = + let input = open_in file_path in + let rec fold accumulator = + let line = + try Some (input_line input) + with End_of_file -> None in + match line with + | Some line -> fold (f accumulator line) + | None -> accumulator in + finally + (fun () -> fold start) + (fun () -> close_in input) + +let file_lines_iter f file_path = + let input = open_in file_path in try while true do - let line = input_line fin in - fn line - done; - close_in fin; + let line = input_line input in + f line + done with - | End_of_file -> close_in fin - | exn -> close_in fin; raise exn + | End_of_file -> close_in input + | exn -> close_in input; raise exn + +let readfile_line = file_lines_iter (** open a file, and make sure the close is always done *) let with_file file mode perms f = diff --git a/stdext/unixext.mli b/stdext/unixext.mli index d35d51b..8008bde 100644 --- a/stdext/unixext.mli +++ b/stdext/unixext.mli @@ -11,6 +11,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) +(** A collection of extensions to the [Unix] module. *) + external _exit : int -> unit = "unix_exit" val unlink_safe : string -> unit val mkdir_safe : string -> Unix.file_perm -> unit @@ -20,6 +22,15 @@ val pidfile_read : string -> int option val daemonize : unit -> unit val with_file : string -> Unix.open_flag list -> Unix.file_perm -> (Unix.file_descr -> 'a) -> 'a val with_directory : string -> (Unix.dir_handle -> 'a) -> 'a + +(** Folds function [f] over every line in the file at [file_path] using the +starting value [start]. *) +val file_lines_fold : ('a -> string -> 'a) -> 'a -> string -> 'a + +(** Applies function [f] to every line in the file at [file_path]. *) +val file_lines_iter : (string -> unit) -> string -> unit + +(** Alias for function [file_lines_iter]. *) val readfile_line : (string -> 'a) -> string -> unit val read_whole_file : int -> int -> Unix.file_descr -> string val read_whole_file_to_string : string -> string