raz / sbcl / lib / Files.raz

46 lines · 1.0 KiB · raw · history · last change 55bc6c0d

1(* An argument as a string, and a whole file read or written. *)
2module Files;
3import Sys, Buf;
4
5(* argument i; 0 is the program's name *)
6proc arg*(i: INT): []U8;
7var s: ^U8; n: INT;
8begin
9 if i < 0 or i >= ARGC() then return ""; end;
10 s := ARGV()[i];
11 while s[n] # 0 do INC(n); end;
12 return s[0..n];
13end;
14
15(* the whole file added to b *)
16proc read*(path: []U8; b: ^Buf.Buf): BOOL;
17var fd, n: INT; chunk: [4096]U8;
18begin
19 fd := Sys.openRead(path);
20 if fd < 0 then return false; end;
21 defer Sys.close(fd);
22 n := Sys.read(fd, chunk);
23 while n > 0 do
24 if not Buf.room(b, n) then return false; end;
25 Buf.str(b, chunk[0..n]);
26 n := Sys.read(fd, chunk);
27 end;
28 return n = 0;
29end;
30
31(* the file made to hold data *)
32proc write*(path, data: []U8): BOOL;
33var fd, n, done: INT;
34begin
35 fd := Sys.create(path);
36 if fd < 0 then return false; end;
37 defer Sys.close(fd);
38 while done < LEN(data) do
39 n := Sys.write(fd, data[done..LEN(data)]);
40 if n <= 0 then return false; end;
41 done := done + n;
42 end;
43 return true;
44end;
45
46end Files.