summaryrefslogtreecommitdiff
path: root/src/cmd/cat/cat.c
diff options
context:
space:
mode:
authorJacob McDonnell <jacob@jacobmcdonnell.com>2024-03-05 18:46:44 -0500
committerJacob McDonnell <jacob@jacobmcdonnell.com>2024-03-05 18:46:44 -0500
commitc40f400f6ab879e08d54de753aabc987fd6ba07a (patch)
tree295f95070362d14d987638b558ad6bb1ba2415e2 /src/cmd/cat/cat.c
parente32262d86c90e2ac73b2c38a47a1bb6b60935098 (diff)
Added a simple shell, jsh
Diffstat (limited to 'src/cmd/cat/cat.c')
-rwxr-xr-xsrc/cmd/cat/cat.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/src/cmd/cat/cat.c b/src/cmd/cat/cat.c
new file mode 100755
index 0000000..1c3e40a
--- /dev/null
+++ b/src/cmd/cat/cat.c
@@ -0,0 +1,54 @@
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdbool.h>
+
+void fileoutput(FILE *, const char *);
+bool isdir(const char *);
+
+/* concatinate files to a file stream */
+int main(int argc, char **argv)
+{
+ FILE *fp;
+ if (argc == 1) {
+ fileoutput(stdin, "stdin");
+ } else {
+ while (--argc > 0 && !ferror(stdout)) {
+ if (isdir(*++argv)) {
+ perror("cat");
+ continue;
+ }
+ if ((fp = fopen(*argv, "r")) == NULL) {
+ perror("cat");
+ continue;
+ }
+ fileoutput(fp, *argv);
+ }
+ }
+ if (ferror(stdout)) {
+ perror("cat");
+ return -1;
+ }
+ return 0;
+}
+
+/* fileoutput: output a file to stdout */
+void fileoutput(FILE *fp, const char *name)
+{
+ int c;
+ while ((c = getc(fp)) != EOF)
+ putc(c, stdout);
+ if (ferror(fp)) {
+ perror("cat");
+ }
+ fclose(fp);
+}
+
+/* isdir: return true if the file as the path is a directory */
+bool isdir(const char *path)
+{
+ struct stat sbuf;
+ stat(path, &sbuf);
+ return S_ISDIR(sbuf.st_mode);
+}
+