summaryrefslogtreecommitdiff
path: root/src/cat.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/cat.c')
-rw-r--r--src/cat.c46
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;
+}