浏览代码

Implement cat tool to better test the pipes

rexim 4 年之前
父节点
当前提交
9c638c58c0
共有 3 个文件被更改,包括 46 次插入1 次删除
  1. 1 0
      examples/pipe.c
  2. 2 1
      tools/.gitignore
  3. 43 0
      tools/cat.c

+ 1 - 0
examples/pipe.c

@@ -7,6 +7,7 @@ int main(void)
           CHAIN_CMD(PATH("tools", "rot13")),
           CHAIN_CMD(PATH("tools", "hex")),
           OUT("output.txt"));
+    CMD(PATH("tools", "cat"), "output.txt");
 
     return 0;
 }

+ 2 - 1
tools/.gitignore

@@ -1,2 +1,3 @@
 hex
-rot13
+rot13
+cat

+ 43 - 0
tools/cat.c

@@ -0,0 +1,43 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+void cat_file(const char *file_path)
+{
+    FILE *f = fopen(file_path, "r");
+    if (f == NULL) {
+        fprintf(stderr, "ERROR: could not open file %s: %s\n",
+                file_path, strerror(errno));
+        exit(1);
+    }
+
+    static char cat_buffer[4098];
+
+    while (!feof(f)) {
+        size_t n = fread(cat_buffer,
+                         sizeof(cat_buffer[0]),
+                         sizeof(cat_buffer) / sizeof(cat_buffer[0]),
+                         f);
+        fwrite(cat_buffer,
+               sizeof(cat_buffer[0]),
+               n,
+               stdout);
+    }
+
+    fclose(f);
+}
+
+int main(int argc, char **argv)
+{
+    if (argc < 2) {
+        fprintf(stderr, "USAGE: cat <files...>");
+        exit(1);
+    }
+
+    for (int i = 1; i < argc; ++i) {
+        cat_file(argv[i]);
+    }
+
+    return 0;
+}