summaryrefslogtreecommitdiff
path: root/42sh/src/builtins/echo.c
diff options
context:
space:
mode:
Diffstat (limited to '42sh/src/builtins/echo.c')
-rw-r--r--42sh/src/builtins/echo.c94
1 files changed, 94 insertions, 0 deletions
diff --git a/42sh/src/builtins/echo.c b/42sh/src/builtins/echo.c
new file mode 100644
index 0000000..f330050
--- /dev/null
+++ b/42sh/src/builtins/echo.c
@@ -0,0 +1,94 @@
+#include <stdio.h>
+#include <string.h>
+
+#include "builtins.h"
+
+static void print_echo(struct string **args, int escapes, int newline, int i)
+{
+ while (args[i] != NULL)
+ {
+ if (escapes)
+ {
+ size_t j = 0;
+ while (j < args[i]->length)
+ {
+ if (args[i]->data[j] == '\\' && args[i]->data[j] != '\0')
+ {
+ j += 1;
+ switch (args[i]->data[j])
+ {
+ case 'n':
+ putchar('\n');
+ break;
+ case 't':
+ putchar('\t');
+ break;
+ case '\\':
+ putchar('\\');
+ break;
+ default:
+ putchar('\\');
+ putchar(args[i]->data[j]);
+ break;
+ }
+ j += 1;
+ }
+ else
+ {
+ putchar(args[i]->data[j]);
+ j += 1;
+ }
+ }
+ }
+ else
+ {
+ fputs(args[i]->data, stdout);
+ }
+ if (args[i + 1] != NULL)
+ {
+ putchar(' ');
+ }
+ i += 1;
+ }
+ if (newline)
+ {
+ putchar('\n');
+ }
+}
+
+int echo(struct string **args)
+{
+ int newline = 1;
+ int escapes = 0;
+ size_t i = 0;
+ if (args[0] == NULL)
+ {
+ putchar('\n');
+ return 0;
+ }
+ while (args[i] != NULL && args[i]->data[0] == '-')
+ {
+ if (args[i]->length == 2 && args[i]->data[1] == 'n')
+ {
+ newline = 0;
+ i += 1;
+ }
+ else if (args[i]->length == 2 && args[i]->data[1] == 'e')
+ {
+ escapes = 1;
+ i += 1;
+ }
+ else if (args[i]->length == 2 && args[i]->data[1] == 'E')
+ {
+ escapes = 0;
+ i += 1;
+ }
+ else
+ {
+ break;
+ }
+ }
+ print_echo(args, escapes, newline, i);
+ fflush(stdout);
+ return 0;
+}