aboutsummaryrefslogtreecommitdiff
path: root/example/cat/main.zig
blob: a24b26822847786b7dec0d55db709c182354021f (plain)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const std = @import("std");
const io = std.io;
const str = std.str;

// TODO var args printing

pub fn main(args: [][]u8) -> %void {
    const exe = args[0];
    var catted_anything = false;
    for (args[1...]) |arg| {
        if (str.eql(arg, "-")) {
            catted_anything = true;
            cat_stream(&io.stdin) %% |err| return err;
        } else if (arg[0] == '-') {
            return usage(exe);
        } else {
            var is: io.InStream = undefined;
            is.open(arg) %% |err| {
                %%io.stderr.printf("Unable to open file: ");
                %%io.stderr.printf(@errorName(err));
                %%io.stderr.printf("\n");
                return err;
            };
            defer %%is.close();

            catted_anything = true;
            cat_stream(&is) %% |err| return err;
        }
    }
    if (!catted_anything) {
        cat_stream(&io.stdin) %% |err| return err;
    }
    io.stdout.flush() %% |err| return err;
}

fn usage(exe: []u8) -> %void {
    %%io.stderr.printf("Usage: ");
    %%io.stderr.printf(exe);
    %%io.stderr.printf(" [FILE]...\n");
    return error.Invalid;
}

fn cat_stream(is: &io.InStream) -> %void {
    var buf: [1024 * 4]u8 = undefined;

    while (true) {
        const bytes_read = is.read(buf) %% |err| {
            %%io.stderr.printf("Unable to read from stream: ");
            %%io.stderr.printf(@errorName(err));
            %%io.stderr.printf("\n");
            return err;
        };

        if (bytes_read == 0) {
            break;
        }

        io.stdout.write(buf[0...bytes_read]) %% |err| {
            %%io.stderr.printf("Unable to write to stdout: ");
            %%io.stderr.printf(@errorName(err));
            %%io.stderr.printf("\n");
            return err;
        };
    }
}