The library · lesson 4 of 18

Files and the command line

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.

A whole file

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.

Notes.raz
module Notes;
import Out, Files, Buf, Heap;

proc main*;
var b: Buf.Buf; ok: BOOL;
begin
    ok := Files.write("notes.txt", "first line\nsecond line\n");
    if not ok then Out.str("can't write\n"); return; end;
    Buf.init(b, Heap.heap);
    defer Buf.done(b);
    ok := Files.read("notes.txt", b);
    if ok then
        Out.int(b.len); Out.str(" bytes: "); Out.str(Buf.bytes(b));
    end;
    ok := Files.read("missing.txt", b);
    if not ok then Out.str("missing.txt: not there\n"); end;
    if Files.load("missing.txt", b) = -2 then Out.str("missing.txt: ENOENT\n"); end;
end;

end Notes.
23 bytes: first line
second line
missing.txt: not there
missing.txt: ENOENT

When 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.

Descriptors

Underneath, 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.

Count.raz
module Count;
import Out, Sys;

(* the lines of the file at path, or minus an errno *)
proc lines(path: []U8): INT;
var fd, n, i, count: INT; buf: [4096]U8;
begin
    fd := Sys.openRead(path);
    if fd < 0 then return fd; end;
    defer Sys.close(fd);
    n := Sys.read(fd, buf);
    while n > 0 do
        for i := 0 to n - 1 do
            if buf[i] = '\n' then INC(count); end;
        end;
        n := Sys.read(fd, buf);
    end;
    if n < 0 then return n; end;
    return count;
end;

proc main*;
var fd: INT; pos: I64;
begin
    fd := Sys.create("log.txt");
    _ := Sys.write(fd, "a\nb\nc\n");
    pos := Sys.seek(fd, 2, false);              (* from the start *)
    Out.int(pos); Out.ln;
    Sys.close(fd);
    Out.int(lines("log.txt")); Out.str(" lines\n");
    Out.int(lines("/no/such/file")); Out.ln;     (* -2: ENOENT *)
    fd := Sys.open("log.txt", {Sys.writing, Sys.appending});
    _ := Sys.write(fd, "d\n");
    Sys.close(fd);
    Out.int(lines("log.txt")); Out.str(" lines now\n");
end;

end Count.
2
3 lines
-2
4 lines now

Looking at a file, and a directory

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.

Tree.raz
module Tree;
import Out, Sys, Str, Heap, Mem, Buf, Order := Sort([]U8, before);

proc before(a, b: []U8): BOOL;
begin
    return Str.cmp(a, b) < 0;
end;

(* a file made to hold text *)
proc put(path, text: []U8);
var fd: INT;
begin
    fd := Sys.create(path);
    _ := Sys.write(fd, text);
    Sys.close(fd);
end;

proc main*;
var
    d: Sys.Dir; name, copy: []U8; more, ok: BOOL; i, n: INT;
    info: Sys.Info; err: INT; names: [16][]U8; path: Buf.Buf;
begin
    _ := Sys.makeDir("proj");
    _ := Sys.makeDir("proj/src");
    put("proj/b.txt", "bb");
    put("proj/a.txt", "a");
    if Sys.openDir(d, "proj") < 0 then return; end;
    n := 0;
    name, more := Sys.nextEntry(d);
    while more do
        copy, ok := Str.copy(Heap.heap, name);
        if ok and (n < 16) then names[n] := copy; INC(n); end;
        name, more := Sys.nextEntry(d);
    end;
    Sys.closeDir(d);
    Order.sort(names[0..n]);
    Buf.init(path, Heap.heap);
    for i := 0 to n - 1 do
        Buf.reset(path);
        Buf.str(path, "proj/");
        Buf.str(path, names[i]);
        info, err := Sys.info(Buf.bytes(path));
        Out.str(names[i]);
        if err < 0 then Out.str(" ?");
        elsif info.dir then Out.str("/");
        else Out.str(", "); Out.int(info.size); Out.str(" bytes");
        end;
        Out.ln;
        Mem.free(Heap.heap, ^U8(ADR(names[i][0])));
    end;
    Buf.done(path);
end;

end Tree.
a.txt, 1 bytes
b.txt, 2 bytes
src/

Modes, links, and a lock

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.

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.

Store.raz
module Store;
import Fmt, Sys;

proc main*;
var fd, other: INT; named, target: Sys.Info;
begin
    fd := Sys.openMode("run.sh", {Sys.writing, Sys.creating, Sys.truncating}, 1EDH);
    _ := Sys.write(fd, "echo hi\n");
    _ := Sys.syncAll(fd);
    Sys.close(fd);
    target, _ := Sys.info("run.sh");
    Fmt.print("its owner may run it: {}\n", [Fmt.bool(target.mode & 40H # 0)]);

    _ := Sys.remove("current");
    _ := Sys.symlink("run.sh", "current");
    named, _ := Sys.linkInfo("current");
    Fmt.print("a link: {}, of {} bytes\n", [Fmt.bool(named.symlink), Fmt.int(named.size)]);
    named, _ := Sys.info("current");
    Fmt.print("the same file: {}\n", [Fmt.bool(named.ino = target.ino)]);

    fd := Sys.openRead("run.sh");
    other := Sys.openRead("run.sh");
    Fmt.print("{} {}\n", [Fmt.int(Sys.lock(fd, false)), Fmt.int(Sys.lock(other, false))]);   (* -11: held *)
    Sys.close(fd);
    Fmt.print("{}\n", [Fmt.int(Sys.lock(other, false))]);   (* free again *)
    Sys.close(other);
end;

end Store.
its owner may run it: true
a link: true, of 6 bytes
the same file: true
0 -11
0

A command line, from a table

A program describes its options once, in a table of Opt.Rows: 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.

Tool.raz
module Tool;
import Out, Fmt, Opt;

const count = 1;                   (* the key of --count, which has no letter *)

proc main*;
var p: Opt.Parser; verbose: BOOL; n, i: INT; w: []U8; ok: BOOL;
begin
    n := 1;
    Opt.init(p, "tool", [
        Opt.usage("", "tool [-v] [--count n] word ..."),
        Opt.option("", 'v', "verbose", "", "say more"),
        Opt.option("", count, "count", "n", "repeat each word n times")]);
    while Opt.next(p) do
        if p.letter = 'v' then verbose := true;
        elsif p.letter = count then n := INT(Opt.number(p, 1, 5));
        end;
    end;
    w, ok := Opt.operand(p);
    if not ok then Opt.fail(p, "no words; see tool -h"); end;
    while ok do
        for i := 1 to n do
            if verbose then Out.str("word: "); end;
            Fmt.print("{}\n", [Fmt.str(w)]);
        end;
        w, ok := Opt.operand(p);
    end;
end;

end Tool.
$ raz Tool.raz
$ ./Tool -h
usage: tool [-v] [--count n] word ...

  -v, --verbose   say more
      --count n   repeat each word n times
  -h, --help      print this and exit
$ ./Tool -v hello world
word: hello
word: world
$ ./Tool --count 9 hello; echo "status $?"
tool: --count wants a number from 1 to 5, not '9'
usage: tool [-v] [--count n] word ...
status 2
$ ./Tool -x; echo "status $?"
tool: unknown option -x
usage: tool [-v] [--count n] word ...
status 2
$ ./Tool; echo "status $?"
tool: no words; see tool -h
status 2

-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.

A 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.

Save a program under its module’s name and run it with raz run Name.raz.