Simpler cat.
This commit is contained in:
		
							parent
							
								
									16d6067f21
								
							
						
					
					
						commit
						9109646d8f
					
				
					 1 changed files with 9 additions and 16 deletions
				
			
		
							
								
								
									
										23
									
								
								src/cat.zig
									
										
									
									
									
								
							
							
						
						
									
										23
									
								
								src/cat.zig
									
										
									
									
									
								
							| 
						 | 
				
			
			@ -1,5 +1,5 @@
 | 
			
		|||
const std = @import("std");
 | 
			
		||||
const lib = @import("./lib.zig");
 | 
			
		||||
const stdout = std.io.getStdOut().writer();
 | 
			
		||||
 | 
			
		||||
pub fn main() anyerror!void {
 | 
			
		||||
    const args = try std.process.argsAlloc(std.heap.page_allocator);
 | 
			
		||||
| 
						 | 
				
			
			@ -8,34 +8,27 @@ pub fn main() anyerror!void {
 | 
			
		|||
        try print_input();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    const files = args[1..];
 | 
			
		||||
    for (files) |f| {
 | 
			
		||||
    for (args[1..]) |f| {
 | 
			
		||||
        if (std.mem.eql(u8, f, "-")) { try print_input();  }
 | 
			
		||||
        else                         { try print_file (f); }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
fn print_input() !void {
 | 
			
		||||
    const stdin = std.io.getStdIn().reader();
 | 
			
		||||
    var buffer: [4096]u8 = undefined;
 | 
			
		||||
    while (true) {
 | 
			
		||||
        const nbytes = try stdin.read(&buffer);
 | 
			
		||||
        lib.print("{s}", .{buffer[0..nbytes]});
 | 
			
		||||
        if (nbytes == 0) break;
 | 
			
		||||
    }
 | 
			
		||||
    try print_all (std.io.getStdIn());
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
fn print_file(dest: []const u8) !void {
 | 
			
		||||
    // open file and defer closing
 | 
			
		||||
    var file = try std.fs.cwd().openFile(dest, .{ .mode = .read_only });
 | 
			
		||||
    defer file.close();
 | 
			
		||||
    try print_all (file);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
    // read file content and print everything
 | 
			
		||||
fn print_all(reader: std.fs.File) !void {
 | 
			
		||||
    var buffer: [4096]u8 = undefined;
 | 
			
		||||
    var nbytes : u64 = 0;
 | 
			
		||||
    while (true) {
 | 
			
		||||
        nbytes = try file.read(&buffer);
 | 
			
		||||
        lib.print("{s}", .{buffer[0..nbytes]});
 | 
			
		||||
        const nbytes = try reader.read(&buffer);
 | 
			
		||||
        try stdout.print("{s}", .{buffer[0..nbytes]});
 | 
			
		||||
        if (nbytes == 0) break;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
		Loading…
	
	Add table
		
		Reference in a new issue