let buffer_size = 8192;; let buffer = String.create buffer_size;;
let file_copy ?(perm=0o666) ?(flag=O_TRUNC) input_name output_name = let fd_in = openfile input_name [O_RDONLY] 0 in let fd_out = openfile output_name [O_WRONLY; O_CREAT; flag] perm in letrec copy_loop () = match read fd_in buffer 0 buffer_size with
0 -> () | r -> ignore (write fd_out buffer 0 r); copy_loop () in
copy_loop ();
close fd_in;
close fd_out;;
end;; (* module Copylib *)
(** Copy a file into another. Optional permissions (by default 0o640) concern of course the target. *)
let file_copy ?(perm=0o640) (x:filename) (y:filename) = Unix.handle_unix_error (Copylib.file_copy ~perm x) y ;;
(** Append a file into another. Optional permissions (by default 0o640) concern of course the target. *)
let file_append ?(perm=0o640) (x:filename) (y:filename) = Unix.handle_unix_error (Copylib.file_copy ~perm ~flag:Unix.O_APPEND x) y ;;
(**
Saving strings
*)
(** Write or rewrite the file with the given content.
If the file does not exists, it is created with the given permission
(set by default to 0o640). *)
let put ?(perm=0o640) (fname:filename) (x:content) : unit = let fd = (Unix.openfile fname [Unix.O_CREAT; Unix.O_WRONLY; Unix.O_TRUNC] perm) in let n = String.length x in
ignore (Unix.write fd x 0 n);
(Unix.close fd)
;;
(** Alias for put. *)
let rewrite = put;;
(** Similar to the function put described above, but the content is appended instead of rewrited.
If the file doesn't exists, it is created with the given permissions (set by default to 0o640). *)
let append ?(perm=0o640) (fname:filename) (x:content) = let fd = (Unix.openfile fname [Unix.O_CREAT; Unix.O_WRONLY; Unix.O_APPEND] perm) in let n = String.length x in
ignore (Unix.write fd x 0 n);
(Unix.close fd)
;;
(**
Loading strings
*)
(** Return the whole content (caution!) of the file
as a string. Use only for small files.
Great for making pipelines. For instance,
the following pipeline catches the first line of /etc/fstab containing
the substring "hda1":
letrec cat (fname:filename) = let fd = (Unix.openfile fname [Unix.O_RDONLY] 0o640) in let len = 16*1024 in let buff = String.create len in letrec boucle () = begin let n = (Unix.read fd buff 0 len) in let s = String.sub buff 0 n in if (n<len) then s else s^(boucle ()) endin
boucle ()
;;
(**
Temporary files
*)
(** Support for this section. *)
moduleTemplib = struct
(** General function for creating temporary files or directories in a parent directory
with some permissions and with a prefix and suffix for the name.
The function returns the name of the created file or directory.
*)
letrec temp_name ~(dir:bool) ~(perm:Unix.file_perm) ~(parent:string) ~(prefix:string) ~(suffix:string) () = begin let rnd = Random.int (1024*1024*1023)&nra" rel="Chapter" href="UnixExtra.html">
UnixExtra.Extrastruct in if (Sys.file_exists candidate) then (temp_name ~dir ~perm ~parent ~prefix ~suffix ()) else begin if dir then (Unix.mkdir candidate perm) else (touch candidate ~perm) ;
candidate end end
;; end