| | @@ -1,7 +1,7 @@ |
| 1 | 1 | (* What most programs need of the command line and of files: an |
| 2 | 2 | argument as a string, and a whole file read or written. *) |
| 3 | 3 | module Files; |
| 4 | | -import Sys, Buf; |
| 4 | +import Sys, Buf, Heap, Rt; |
| 5 | 5 | |
| 6 | 6 | (* Argument i, a C string, as a slice. *) |
| 7 | 7 | proc arg*(i: INT): []U8; |
| | @@ -13,20 +13,29 @@ |
| 13 | 13 | return s[0..n]; |
| 14 | 14 | end; |
| 15 | 15 | |
| 16 | | -(* Adds the file at path to b; false if it can't be read. *) |
| 17 | | -proc read*(path: []U8; b: ^Buf.Buf): BOOL; |
| 16 | +(* Adds the file at path to b: 0, or minus the errno of the open or |
| 17 | + the read that failed, as Sys gives them: -2 (ENOENT) for no such |
| 18 | + file, -13 (EACCES) for one not allowed, -21 (EISDIR) for a |
| 19 | + directory. What was read before a read failed stays in b. *) |
| 20 | +proc load*(path: []U8; b: ^Buf.Buf): INT; |
| 18 | 21 | var fd, n: INT; |
| 19 | 22 | begin |
| 20 | 23 | fd := Sys.openRead(path); |
| 21 | | - if fd < 0 then return false; end; |
| 24 | + if fd < 0 then return fd; end; |
| 22 | 25 | repeat |
| 23 | 26 | n := Sys.read(fd, Buf.spare(b, 65536)); (* straight into b *) |
| 24 | 27 | if n > 0 then INC(b^.len, n); end; |
| 25 | 28 | until n <= 0; |
| 26 | 29 | Sys.close(fd); |
| 27 | | - return n = 0; |
| 30 | + return n; |
| 28 | 31 | end; |
| 29 | 32 | |
| 33 | +(* Adds the file at path to b; false if it can't be read. *) |
| 34 | +proc read*(path: []U8; b: ^Buf.Buf): BOOL; |
| 35 | +begin |
| 36 | + return load(path, b) = 0; |
| 37 | +end; |
| 38 | + |
| 30 | 39 | (* Makes the file at path hold data; false if it can't be written. *) |
| 31 | 40 | proc write*(path, data: []U8): BOOL; |
| 32 | 41 | var fd, n, at: INT; |
| | @@ -41,6 +50,21 @@ |
| 41 | 50 | end; |
| 42 | 51 | Sys.close(fd); |
| 43 | 52 | return true; |
| 53 | +end; |
| 54 | + |
| 55 | +(* The module's test. *) |
| 56 | +proc main*; |
| 57 | +var b: Buf.Buf; |
| 58 | +begin |
| 59 | + Buf.init(ADR(b), Heap.heap); |
| 60 | + if not write("/tmp/raz-files-test", "abc") then Rt.stop("Files.write"); end; |
| 61 | + if (load("/tmp/raz-files-test", ADR(b)) # 0) or (Buf.bytes(ADR(b)) # "abc") then Rt.stop("Files.load"); end; |
| 62 | + if not read("/tmp/raz-files-test", ADR(b)) or (Buf.bytes(ADR(b)) # "abcabc") then Rt.stop("Files.read"); end; |
| 63 | + _ := Sys.remove("/tmp/raz-files-test"); |
| 64 | + if load("/tmp/raz-files-test", ADR(b)) # -2 then Rt.stop("Files.load: no such file"); end; |
| 65 | + if load("/", ADR(b)) # -21 then Rt.stop("Files.load: a directory"); end; |
| 66 | + if read("/", ADR(b)) or (b.len # 6) then Rt.stop("Files.read: a directory"); end; |
| 67 | + Buf.done(ADR(b)); |
| 44 | 68 | end; |
| 45 | 69 | |
| 46 | 70 | end Files. |