From b3c96cc961404fea566c2cdde320008a33984284 Mon Sep 17 00:00:00 2001 From: Armaan Bhojwani Date: Sat, 15 May 2021 10:42:11 -0400 Subject: [PATCH] morse: add program Converts ASCII input to morse code --- morse.c | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 morse.c diff --git a/morse.c b/morse.c new file mode 100644 index 0000000..27e0fa6 --- /dev/null +++ b/morse.c @@ -0,0 +1,56 @@ +/* Convert ASCII to morse code. Reads from stdin if provided with no argument + or "-", otherwise reads from the first command line argument. Prints "*" if + character is not found. */ + +#include +#include +#include +#include + +const char *aa[] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", + "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", + "2", "3", "4", "5", "6", "7", "8", "9", "0", " "}; + +const char *ma[] = {"•-", "-•••", "-•-•", "-••", "•", "••-•", "--•", "••••", + "••", "•---", "-•-", "•-••", "--", "-•", "---", "•--•", "--•-", "•-•", "•••", + "-", "•--", "•••-", "•--", "-••-", "-•--", "--••", "•----", "••---", "•••--", + "••••-", "•••••", "-••••", "--•••", "---••", "----•", "-----", " "}; + +void +convert(char *c) +{ + if (strcmp(c, "\n") == 0) { + printf("\n"); + return; + } + + for (int i = 0; aa[i]; i++) { + if (strcmp(c, aa[i]) == 0) { + printf("%s", ma[i]); + break; + } else if (i == sizeof(aa)/sizeof(char *) - 1) { + printf("*"); + } + } + printf(" "); +} + +int +main(int argc, char **argv) +{ + char c[2]; + c[1] = '\0'; + + if (argv[1] && strcmp(argv[1], "-") != 0) { + for (int i = 0; argv[1][i]; i++) { + c[0] = argv[1][i]; + convert(c); + } + } else { + while (read(STDIN_FILENO, &c[0], 1) > 0) { + convert(c); + } + } + printf("\n"); + return 0; +} -- 2.39.2