micro-utils/src/echo.c

95 lines
1.1 KiB
C
Raw Normal View History

2024-07-01 10:23:00 +00:00
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
2024-07-09 12:43:55 +00:00
static char n_flag = 0;
static char e_flag = 0;
2024-07-01 10:23:00 +00:00
2024-07-09 12:43:55 +00:00
static void format(char *str) {
2024-07-01 10:23:00 +00:00
for (size_t i = 0; i < strlen(str); i++) {
unsigned int c = str[i];
if (c == '\\') {
switch (str[i + 1]) {
case 'a':
c = '\a';
break;
case 'n':
c = '\n';
break;
case 't':
c = '\t';
break;
case 'c':
exit(0);
case 'v':
c = '\v';
break;
case 'r':
c = '\r';
break;
case 'f':
c = '\f';
break;
case 'e':
c = '\033';
break;
case 'b':
c = '\b';
break;
default:
c = '\\';
}
i++;
}
putchar(c);
}
}
int main(int argc, char **argv) {
argv++;
argc--;
for (int i = 0; i < argc; i++) {
if (argv[i][0] == '-') {
if (strstr(argv[i] + 1, "n"))
n_flag = 1;
else if (strstr(argv[i] + 1, "e"))
e_flag = 1;
argc--;
argv++;
}
}
for (int i = 0; i < argc; i++) {
if (e_flag)
format(argv[i]);
else
fputs(argv[i], stdout);
if (i < argc - 1)
putchar(' ');
}
if (!n_flag)
putchar('\n');
return 0;
}