commit cb98d9607e45ec1cd3469a731bc4dc3f9f5ad01a
parent bed094ca7c1be13351cfe65479311c4f7ba0c6c2
Author: aabacchus <ben@bvnf.space>
Date: Thu, 16 Sep 2021 02:45:50 +0100
cat: add
Diffstat:
M | Makefile | | | 2 | +- |
A | cat.c | | | 58 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
2 files changed, 59 insertions(+), 1 deletion(-)
diff --git a/Makefile b/Makefile
@@ -1,6 +1,6 @@
.POSIX:
-BINS =
+BINS = cat
XCFLAGS = $(CFLAGS) -Wall -Wextra -Wpedantic -g
.PHONY: clean
diff --git a/cat.c b/cat.c
@@ -0,0 +1,58 @@
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#define BUF_SIZE 4096
+
+int
+cat(int fd, char *fname) {
+ unsigned char buf[BUF_SIZE];
+ ssize_t n;
+ while ((n = read(fd, buf, BUF_SIZE)) > 0) {
+ if (n == -1){
+ fprintf(stderr, "cat: read %s: %s\n", fname, strerror(errno));
+ return 1;
+ }
+ if (write(1, buf, n) == -1) {
+ fprintf(stderr, "cat: write: %s\n", strerror(errno));
+ return 1;
+ }
+ }
+ return 0;
+}
+
+int
+main(int argc, char **argv) {
+ if (argc == 1)
+ return cat(0, "stdin");
+
+ int fd;
+ int err = 0;
+ char *fname;
+
+ while (*++argv) {
+ if (**argv == '-') {
+ fd = 0;
+ fname = "stdin";
+ } else {
+ fd = open(*argv, O_RDONLY);
+ if (fd == -1) {
+ fprintf(stderr, "cat: open %s: %s\n", *argv, strerror(errno));
+ err = 1;
+ continue;
+ }
+ fname = *argv;
+ }
+ if (cat(fd, fname) != 0) {
+ err = 1;
+ continue;
+ }
+ if (close(fd) == -1){
+ fprintf(stderr, "cat: close %s: %s\n", fname, strerror(errno));
+ err = 1;
+ }
+ }
+ return err;
+}