zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

blob fa45f2a8 (1777B) - Raw


      1 const std = @import("std");
      2 const io = std.io;
      3 const str = std.str;
      4 
      5 // TODO var args printing
      6 
      7 pub fn main(args: [][]u8) -> %void {
      8     const exe = args[0];
      9     var catted_anything = false;
     10     for (args[1...]) |arg| {
     11         if (str.eql(arg, "-")) {
     12             catted_anything = true;
     13             cat_stream(io.stdin) %% |err| return err;
     14         } else if (arg[0] == '-') {
     15             return usage(exe);
     16         } else {
     17             var is: io.InStream = undefined;
     18             is.open(arg) %% |err| {
     19                 %%io.stderr.printf("Unable to open file: ");
     20                 %%io.stderr.printf(@errName(err));
     21                 %%io.stderr.printf("\n");
     22                 return err;
     23             };
     24             defer %%is.close();
     25 
     26             catted_anything = true;
     27             cat_stream(is) %% |err| return err;
     28         }
     29     }
     30     if (!catted_anything) {
     31         cat_stream(io.stdin) %% |err| return err;
     32     }
     33     io.stdout.flush() %% |err| return err;
     34 }
     35 
     36 fn usage(exe: []u8) -> %void {
     37     %%io.stderr.printf("Usage: ");
     38     %%io.stderr.printf(exe);
     39     %%io.stderr.printf(" [FILE]...\n");
     40     return error.Invalid;
     41 }
     42 
     43 fn cat_stream(is: io.InStream) -> %void {
     44     var buf: [1024 * 4]u8 = undefined;
     45 
     46     while (true) {
     47         const bytes_read = is.read(buf) %% |err| {
     48             %%io.stderr.printf("Unable to read from stream: ");
     49             %%io.stderr.printf(@errName(err));
     50             %%io.stderr.printf("\n");
     51             return err;
     52         };
     53 
     54         if (bytes_read == 0) {
     55             break;
     56         }
     57 
     58         io.stdout.write(buf[0...bytes_read]) %% |err| {
     59             %%io.stderr.printf("Unable to write to stdout: ");
     60             %%io.stderr.printf(@errName(err));
     61             %%io.stderr.printf("\n");
     62             return err;
     63         };
     64     }
     65 }