diff options
| author | Jake Mannens <jakem_5@hotmail.com> | 2020-03-25 13:21:37 +1100 |
|---|---|---|
| committer | Jake Mannens <jakem_5@hotmail.com> | 2020-03-25 13:21:37 +1100 |
| commit | ddb2cfd8a74670382e61bad0b567f3d30e9aea70 (patch) | |
| tree | f3208f7ff10a187442c26a48a0d68c5b134ef7db /src/cat.c | |
Diffstat (limited to 'src/cat.c')
| -rw-r--r-- | src/cat.c | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/cat.c b/src/cat.c new file mode 100644 index 0000000..bf618cc --- /dev/null +++ b/src/cat.c @@ -0,0 +1,46 @@ +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#define error(...) ({ \ + printf(__VA_ARGS__); \ + exit(EXIT_FAILURE); \ + }) + +static void cat(char *s) { + int fd = STDIN_FILENO; + ssize_t in, out; + char buf[1024]; + + if(strcmp(s, "-")) { + fd = open(s, O_RDONLY); + if(fd < 0) + error("Error opening %s: %s\n", s, strerror(errno)); + } + + for(;;) { + in = read(fd, buf, sizeof(buf)); + if(in < 0) + error("Error reading %s: %s\n", s, strerror(errno)); + out = write(STDOUT_FILENO, buf, in); + if(out < in) + error("Error writiing output: %s\n", strerror(errno)); + if(!in) + return; + } +} + +int main(int argc, char **argv) { + if(argc == 1) { + cat("-"); + return 0; + } + + while(argc-- > 1) + cat(*(++argv)); + + return 0; +} |
