echo.c (1015B)
- // utils-std: Collection of commonly available Unix tools
- // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- #define _POSIX_C_SOURCE 200809L
- #include <stdbool.h>
- #include <stdio.h> // perror
- #include <string.h> // strlen
- #include <unistd.h> // write
- int
- main(int argc, char *argv[])
- {
- size_t arg_len = 0;
- bool opt_n = false;
- argc--;
- argv++;
- if(argc > 0 && strncmp(*argv, "-n", 3) == 0)
- {
- opt_n = true;
- argc--;
- argv++;
- }
- for(int i = 0; i < argc; i++)
- {
- size_t len = strlen(argv[i]);
- argv[i][len] = ' ';
- arg_len += len + 1; // str + space
- }
- if(arg_len == 0)
- {
- if(opt_n) return 0;
- if(write(1, "\n", 1) < 1)
- {
- perror("echo: error: Failed writing");
- return 1;
- }
- return 0;
- }
- else
- argv[0][arg_len - 1] = '\n';
- if(opt_n) arg_len--; // no newline
- ssize_t nwrite = write(1, *argv, arg_len);
- if(nwrite < (ssize_t)arg_len)
- {
- perror("echo: error: Failed writing");
- return 1;
- }
- return 0;
- }