raz / site / content / advanced / 04-files.txt

229 lines · 8.1 KiB · raw · history · last change a5145f64

1title: Files and the command line
2part: The library
3summary: Whole files with Files, descriptors and directories with Sys, and options with Opt.
4---
5`Files` is for the common case: a whole file read or written in one call. `Sys` is the system underneath, for everything else. `Opt` reads a command line from a table, so that the help and the error messages can't drift from the code.
6
7## A whole file
8
9`Files.write(path, data)` makes the file hold `data`, and `Files.read(path, b)` adds the whole file to a `Buf`. Both say whether they worked.
10
11```raz Notes run
12module Notes;
13import Out, Files, Buf, Heap;
14
15proc main*;
16var b: Buf.Buf; ok: BOOL;
17begin
18 ok := Files.write("notes.txt", "first line\nsecond line\n");
19 if not ok then Out.str("can't write\n"); return; end;
20 Buf.init(b, Heap.heap);
21 defer Buf.done(b);
22 ok := Files.read("notes.txt", b);
23 if ok then
24 Out.int(b.len); Out.str(" bytes: "); Out.str(Buf.bytes(b));
25 end;
26 ok := Files.read("missing.txt", b);
27 if not ok then Out.str("missing.txt: not there\n"); end;
28 if Files.load("missing.txt", b) = -2 then Out.str("missing.txt: ENOENT\n"); end;
29end;
30
31end Notes.
32```
33
34When the reason matters, `Files.load` says it: 0, or minus the errno of what failed, -2 (ENOENT) for no such file, -13 (EACCES) for one not allowed.
35
36## Descriptors
37
38Underneath, a file is a descriptor, an `INT`. `Sys.open` takes the path and the way to open it as a set; `read`, `write`, `seek` and `close` do what they say. A result that can fail is a number, and minus an errno if it failed, as on Linux itself. Reading in a loop is the pattern for anything too big to hold at once.
39
40```raz Count run
41module Count;
42import Out, Sys;
43
44(* the lines of the file at path, or minus an errno *)
45proc lines(path: []const U8): INT;
46var fd, n, i, count: INT; buf: [4096]U8;
47begin
48 fd := Sys.openRead(path);
49 if fd < 0 then return fd; end;
50 defer Sys.close(fd);
51 n := Sys.read(fd, buf);
52 while n > 0 do
53 for i := 0 to n - 1 do
54 if buf[i] = '\n' then INC(count); end;
55 end;
56 n := Sys.read(fd, buf);
57 end;
58 if n < 0 then return n; end;
59 return count;
60end;
61
62proc main*;
63var fd: INT; pos: I64;
64begin
65 fd := Sys.create("log.txt");
66 _ := Sys.write(fd, "a\nb\nc\n");
67 pos := Sys.seek(fd, 2, false); (* from the start *)
68 Out.int(pos); Out.ln;
69 Sys.close(fd);
70 Out.int(lines("log.txt")); Out.str(" lines\n");
71 Out.int(lines("/no/such/file")); Out.ln; (* -2: ENOENT *)
72 fd := Sys.open("log.txt", {Sys.writing, Sys.appending});
73 _ := Sys.write(fd, "d\n");
74 Sys.close(fd);
75 Out.int(lines("log.txt")); Out.str(" lines now\n");
76end;
77
78end Count.
79```
80
81## Looking at a file, and a directory
82
83`Sys.info` says a file's size, modification time, permissions, and whether it is a directory, a regular file or a link. `Sys.openDir` and `nextEntry` list a directory, in no particular order, so a program that prints one sorts it first. A name from `nextEntry` is good only until the next call, so the program keeps a copy.
84
85```raz Tree run
86module Tree;
87import Out, Sys, Str, Heap, Mem, Buf, Order := Sort([]U8, before);
88import SYSTEM;
89
90proc before(a, b: []U8): BOOL;
91begin
92 return Str.cmp(a, b) < 0;
93end;
94
95(* a file made to hold text *)
96proc put(path, text: []const U8);
97var fd: INT;
98begin
99 fd := Sys.create(path);
100 _ := Sys.write(fd, text);
101 Sys.close(fd);
102end;
103
104proc main*;
105var
106 d: Sys.Dir; name: []const U8; copy: []U8; more, ok: BOOL; i, n: INT;
107 info: Sys.Info; err: INT; names: [16][]U8; path: Buf.Buf;
108begin
109 _ := Sys.makeDir("proj");
110 _ := Sys.makeDir("proj/src");
111 put("proj/b.txt", "bb");
112 put("proj/a.txt", "a");
113 if Sys.openDir(d, "proj") < 0 then return; end;
114 n := 0;
115 name, more := Sys.nextEntry(d);
116 while more do
117 copy, ok := Str.copy(Heap.heap, name);
118 if ok and (n < 16) then names[n] := copy; INC(n); end;
119 name, more := Sys.nextEntry(d);
120 end;
121 Sys.closeDir(d);
122 Order.sort(names[0..n]);
123 Buf.init(path, Heap.heap);
124 for i := 0 to n - 1 do
125 Buf.reset(path);
126 Buf.str(path, "proj/");
127 Buf.str(path, names[i]);
128 info, err := Sys.info(Buf.bytes(path));
129 Out.str(names[i]);
130 if err < 0 then Out.str(" ?");
131 elsif info.dir then Out.str("/");
132 else Out.str(", "); Out.int(info.size); Out.str(" bytes");
133 end;
134 Out.ln;
135 Mem.free(Heap.heap, ^U8(SYSTEM.ADR(names[i][0])));
136 end;
137 Buf.done(path);
138end;
139
140end Tree.
141```
142
143## Modes, links, and a lock
144
145`Sys.openMode` is `open` with the permissions a file it makes should have, less those the umask takes away: 1EDH (755) for a script, 124H (444) for a file never to be written. `Sys.linkInfo` looks at a symbolic link itself, where `info` follows it, so a link whose target is gone is still seen. `Info.ino` is the file's inode: a file renamed over another has a new one, though its size and time may match, which is how a program knows a file it cached is still the same.
146
147`Sys.lock` takes the lock on an open file, which one open file holds at a time; another that asks for it waits, or with `wait` false gets -11 at once. The lock goes when the file is closed or the program ends, however it ends, so it can't go stale as a lock file can. `Sys.syncAll` puts everything written to a file system on the disk at once, before the one file that names it all is written: a database's or a version control system's commit.
148
149```raz Store run
150module Store;
151import Fmt, Sys;
152
153proc main*;
154var fd, other: INT; named, target: Sys.Info;
155begin
156 fd := Sys.openMode("run.sh", {Sys.writing, Sys.creating, Sys.truncating}, 1EDH);
157 _ := Sys.write(fd, "echo hi\n");
158 _ := Sys.syncAll(fd);
159 Sys.close(fd);
160 target, _ := Sys.info("run.sh");
161 Fmt.print("its owner may run it: {}\n", [Fmt.bool(target.mode & 40H # 0)]);
162
163 _ := Sys.remove("current");
164 _ := Sys.symlink("run.sh", "current");
165 named, _ := Sys.linkInfo("current");
166 Fmt.print("a link: {}, of {} bytes\n", [Fmt.bool(named.symlink), Fmt.int(named.size)]);
167 named, _ := Sys.info("current");
168 Fmt.print("the same file: {}\n", [Fmt.bool(named.ino = target.ino)]);
169
170 fd := Sys.openRead("run.sh");
171 other := Sys.openRead("run.sh");
172 Fmt.print("{} {}\n", [Fmt.int(Sys.lock(fd, false)), Fmt.int(Sys.lock(other, false))]); (* -11: held *)
173 Sys.close(fd);
174 Fmt.print("{}\n", [Fmt.int(Sys.lock(other, false))]); (* free again *)
175 Sys.close(other);
176end;
177
178end Store.
179```
180
181## A command line, from a table
182
183A program describes its options once, in a table of `Opt.Row`s: its synopsis lines, its subcommands and its options. The help and the error messages are made from the table. The parser reads by the rules of the C library's `getopt` with GNU's long options, so `-vn3`, `-n 3`, `--count=3` and `--count 3` all work, and `--` ends the options.
184
185```raz Tool
186module Tool;
187import Out, Fmt, Opt;
188
189const count = 1; (* the key of --count, which has no letter *)
190
191proc main*;
192var p: Opt.Parser; verbose: BOOL; n, i: INT; w: []const U8; ok: BOOL;
193begin
194 n := 1;
195 Opt.init(p, "tool", [
196 Opt.usage("", "tool [-v] [--count n] word ..."),
197 Opt.option("", 'v', "verbose", "", "say more"),
198 Opt.option("", count, "count", "n", "repeat each word n times")]);
199 while Opt.next(p) do
200 if p.letter = 'v' then verbose := true;
201 elsif p.letter = count then n := INT(Opt.number(p, 1, 5));
202 end;
203 end;
204 w, ok := Opt.operand(p);
205 if not ok then Opt.fail(p, "no words; see tool -h"); end;
206 while ok do
207 for i := 1 to n do
208 if verbose then Out.str("word: "); end;
209 Fmt.print("{}\n", [Fmt.str(w)]);
210 end;
211 w, ok := Opt.operand(p);
212 end;
213end;
214
215end Tool.
216```
217
218```sh
219$ raz Tool.raz
220$ ./Tool -h
221$ ./Tool -v hello world
222$ ./Tool --count 9 hello; echo "status $?"
223$ ./Tool -x; echo "status $?"
224$ ./Tool; echo "status $?"
225```
226
227`-h` and `--help` are `Opt`'s: the program never sees them. A mistake on the command line is a sentence on standard error with the program's name first, then the synopsis, and status 2. Nothing in `Tool` wrote any of that.
228
229A mistake in the table itself, such as an option given twice, is the program's, and `init` says so and ends with status 1 before it reads a word.