aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--8.1/Makefile13
-rw-r--r--8.1/error.c17
-rw-r--r--8.1/error.h1
-rw-r--r--8.1/filecopy.c16
-rw-r--r--8.1/filecopy.h1
-rw-r--r--8.1/main.c25
6 files changed, 73 insertions, 0 deletions
diff --git a/8.1/Makefile b/8.1/Makefile
new file mode 100644
index 0000000..84ef405
--- /dev/null
+++ b/8.1/Makefile
@@ -0,0 +1,13 @@
+objects = main.o filecopy.o error.o
+CC = gcc
+CFLAGS = -Wvla -Wall -Wextra -Wstrict-prototypes -Wmissing-prototypes -fsanitize=address
+
+cat : $(objects)
+ $(CC) $(CFLAGS) -o cat $(objects)
+
+main.o : error.h
+filecopy.o : error.h
+
+.PHONY : clean
+clean:
+ rm -f cat $(objects)
diff --git a/8.1/error.c b/8.1/error.c
new file mode 100644
index 0000000..85cd7f0
--- /dev/null
+++ b/8.1/error.c
@@ -0,0 +1,17 @@
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include "error.h"
+
+void error(char *fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+
+ fprintf(stderr, "error: ");
+ vfprintf(stderr, fmt, args);
+ fprintf(stderr, "\n");
+
+ va_end(args);
+ exit(1);
+}
diff --git a/8.1/error.h b/8.1/error.h
new file mode 100644
index 0000000..e862ac8
--- /dev/null
+++ b/8.1/error.h
@@ -0,0 +1 @@
+void error(char *fmt, ...);
diff --git a/8.1/filecopy.c b/8.1/filecopy.c
new file mode 100644
index 0000000..b35ccbd
--- /dev/null
+++ b/8.1/filecopy.c
@@ -0,0 +1,16 @@
+#include <stdio.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include "filecopy.h"
+#include "error.h"
+
+void filecopy(int ifd, int ofd)
+{
+ ssize_t n;
+ char buff[BUFSIZ];
+
+ while ((n = read(ifd, buff, BUFSIZ)) > 0)
+ if (write(ofd, buff, n) != n)
+ error("cat: write error");
+}
diff --git a/8.1/filecopy.h b/8.1/filecopy.h
new file mode 100644
index 0000000..22b0546
--- /dev/null
+++ b/8.1/filecopy.h
@@ -0,0 +1 @@
+void filecopy(int ifd, int ofd);
diff --git a/8.1/main.c b/8.1/main.c
new file mode 100644
index 0000000..e3e5dd1
--- /dev/null
+++ b/8.1/main.c
@@ -0,0 +1,25 @@
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include "filecopy.h"
+#include "error.h"
+
+int main(int argc, char *argv[])
+{
+ ssize_t fd;
+
+ if (argc == 1) {
+ filecopy(STDIN_FILENO, STDOUT_FILENO);
+ } else {
+ while (--argc > 0) {
+ if ((fd = open(*++argv, O_RDONLY)) == -1) {
+ error("cp: can't open %s", *argv);
+ } else {
+ filecopy(fd, STDOUT_FILENO);
+ close(fd);
+ }
+ }
+ }
+
+ return 0;
+}