commit 34f463cf39e4caf4a1e5aeeffd6b64721cb22d4d
Author: dwrz <dwrz@dwrz.net>
Date: Tue, 6 Dec 2022 17:14:31 +0000
Add cat.c
Diffstat:
A | 01-cat.c | | | 44 | ++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 44 insertions(+), 0 deletions(-)
diff --git a/01-cat.c b/01-cat.c
@@ -0,0 +1,44 @@
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+// cat takes N file names as command-line arguments, concatenates their
+// contents, and writes the result to its standard output.
+
+static char buf[4096];
+
+int main(int argc, char *argv[]) {
+ for (int i = 0; i < argc; ++i) {
+ // Skip the first argument (program name).
+ if (i == 0) continue;
+
+ // Open the file.
+ int fd = open(argv[i], O_RDONLY);
+ if (fd == 0) {
+ perror("failed to open");
+ exit(1);
+ }
+
+ // Read the file into the buffer, then print it to stdout.
+ ssize_t count;
+ while ((count = read(fd, &buf, sizeof(buf))) != 0) {
+ if (count < 1) {
+ perror("failed to read");
+ exit(1);
+ }
+ // To prevent printing contents from a read that
+ // didn't fill the buffer, terminate the string.
+ if ((size_t) count < sizeof(buf)) {
+ buf[count] = '\0';
+ }
+
+ printf("%s", buf);
+ };
+
+ // Close the file descriptor.
+ if (close(fd) != 0) {
+ perror("failed to close");
+ }
+ }
+}