summaryrefslogtreecommitdiff
path: root/src/commands/echo.c
diff options
context:
space:
mode:
authorTyler Murphy <tylerm@tylerm.dev>2023-04-27 19:06:40 -0400
committerTyler Murphy <tylerm@tylerm.dev>2023-04-27 19:06:40 -0400
commitd373867c238474a68ecce77e3ca5c698dd3b3838 (patch)
treee6d7c178e534e30215b6a5c61d8c121447cf2076 /src/commands/echo.c
parentmakefile (diff)
downloadlazysphere-d373867c238474a68ecce77e3ca5c698dd3b3838.tar.gz
lazysphere-d373867c238474a68ecce77e3ca5c698dd3b3838.tar.bz2
lazysphere-d373867c238474a68ecce77e3ca5c698dd3b3838.zip
add echo and pritnf
Diffstat (limited to 'src/commands/echo.c')
-rw-r--r--src/commands/echo.c103
1 files changed, 103 insertions, 0 deletions
diff --git a/src/commands/echo.c b/src/commands/echo.c
new file mode 100644
index 0000000..b80f872
--- /dev/null
+++ b/src/commands/echo.c
@@ -0,0 +1,103 @@
+#include "../command.h"
+
+#include <stdio.h>
+#include <string.h>
+
+static void print_with_escape_codes(const char* str) {
+
+ size_t index = 0;
+ while (true) {
+ char c = str[index];
+ index++;
+
+ if (c == '\0') break;
+ if (c != '\\') {
+ putchar(c);
+ continue;
+ }
+
+ char n = str[index];
+ index++;
+
+ switch (n) {
+ case '\\':
+ putchar('\\');
+ break;
+ case 'b':
+ putchar('\b');
+ break;
+ case 'c':
+ exit(EXIT_SUCCESS);
+ case 'n':
+ putchar('\n');
+ break;
+ case 'r':
+ putchar('\r');
+ break;
+ case 't':
+ putchar('\t');
+ break;
+ case 'v':
+ putchar('\v');
+ break;
+ default:
+ putchar(c);
+ putchar(n);
+ }
+ }
+}
+
+COMMAND(echo) {
+
+ if (argc < 1) {
+ return EXIT_SUCCESS;
+ }
+
+ bool escape_codes = false;
+ bool newline = true;
+
+ int start = 0;
+
+ if (prefix("-", argv[0])) {
+
+ start = 1;
+
+ for (size_t i = 0; i < strlen(argv[0] + 1); i++) {
+ char c = argv[0][i + 1];
+ switch (c) {
+ case 'e':
+ escape_codes = true;
+ break;
+ case 'E':
+ escape_codes = false;
+ break;
+ case 'n':
+ newline = false;
+ break;
+ default:
+ escape_codes = false;
+ newline = true;
+ start = 0;
+ break;
+ }
+ }
+ }
+
+ for (int i = start; i < argc; i++) {
+ if (escape_codes) {
+ print_with_escape_codes(argv[i]);
+ } else {
+ printf("%s", argv[i]);
+ }
+
+ if (i + 1 != argc) {
+ putchar(' ');
+ }
+ }
+
+ if (newline) {
+ putchar('\n');
+ }
+
+ return EXIT_SUCCESS;
+}