logo

utils-std

Collection of commonly available Unix tools
commit: 72625f923bf81fb977264cecb90ac8c0c86d8a94
parent efb556f123a37119d65cf0d3d9dadd2c24d41905
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Tue, 30 Jul 2024 04:37:52 +0200

cmd/echo: simplify via editing argv in place

Diffstat:

Mcmd/echo.c58+++++++++++++++++-----------------------------------------
1 file changed, 17 insertions(+), 41 deletions(-)

diff --git a/cmd/echo.c b/cmd/echo.c @@ -3,31 +3,34 @@ // SPDX-License-Identifier: MPL-2.0 #define _POSIX_C_SOURCE 200809L -#include <errno.h> #include <stdbool.h> -#include <stdio.h> // fprintf -#include <stdlib.h> // malloc -#include <string.h> // strerror, strlen +#include <stdio.h> // perror +#include <string.h> // strlen #include <unistd.h> // write int main(int argc, char *argv[]) { size_t arg_len = 0; - char *buffer, *buffer_p; - int err = 0; bool opt_n = false; - if((argc >= 2) && (strncmp(argv[1], "-n", 3) == 0)) + argc--; + argv++; + + if(argc > 0 && strncmp(*argv, "-n", 3) == 0) { opt_n = true; argc--; argv++; } - for(int i = 1; i < argc; i++) + for(int i = 0; i < argc; i++) { - arg_len += strlen(argv[i]) + 1; // str + space|newline + size_t len = strlen(argv[i]); + + if(len > 0) argv[i][len] = (i + 1) == argc ? '\n' : ' '; + + arg_len += len + 1; // str + space|newline } if(arg_len == 0) @@ -36,7 +39,7 @@ main(int argc, char *argv[]) if(write(1, "\n", 1) < 1) { - fprintf(stderr, "echo: Write error: %s\n", strerror(errno)); + perror("echo: Write error"); return 1; } @@ -45,39 +48,12 @@ main(int argc, char *argv[]) if(opt_n) arg_len--; // no newline - buffer = malloc(arg_len); - if(buffer == NULL) - { - fprintf(stderr, "echo: Memory allocation error, malloc(%zu): %s\n", arg_len, strerror(errno)); - return 1; - } - - buffer_p = buffer; - for(int i = 1; i < argc; i++) - { - size_t len = strlen(argv[i]); - memcpy(buffer_p, argv[i], len); - buffer_p += len; - - if(i < argc - 1) - { - *buffer_p++ = ' '; - } - } - if(!opt_n) *buffer_p++ = '\n'; - - ssize_t nwrite = write(1, buffer, arg_len); + ssize_t nwrite = write(1, *argv, arg_len); if(nwrite < (ssize_t)arg_len) { - fprintf(stderr, - "echo: Write error, write(1, buffer, %zu) = %zd: %s\n", - arg_len, - nwrite, - strerror(errno)); - err++; + perror("echo: Write error"); + return 1; } - free(buffer); - - return err; + return 0; }