File: append.ml

package info (click to toggle)
js-of-ocaml 6.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,932 kB
  • sloc: ml: 135,957; javascript: 58,364; ansic: 437; makefile: 422; sh: 12; perl: 4
file content (42 lines) | stat: -rw-r--r-- 782 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
(* TEST
   include unix;
   hasunix;
   {
     bytecode;
   }{
     native;
   }
*)

let str = "Hello, OCaml!"

let append () =
  let fd =
    Unix.openfile "append.txt"
      [ Unix.O_WRONLY; Unix.O_CREAT; Unix.O_APPEND ]
      0o644
  in
  let len = String.length str in
  let rec f = function
    | 0 -> ()
    | rem ->
        let n = Unix.write_substring fd str (len - rem) rem in
        f (rem - n)
  in
  f len;
  Unix.close fd

let () =
  append ();
  append ();
  let fd = Unix.openfile "append.txt" [ Unix.O_RDONLY ] 0o644 in
  let buf = Buffer.create 10 in
  let b = Bytes.create 10 in
  let rec f () =
    let n = Unix.read fd b 0 10 in
    Buffer.add_subbytes buf b 0 n;
    if n <> 0 then f ()
  in
  f ();
  Unix.close fd;
  assert (Buffer.contents buf = str ^ str)