echo.c (1107B)
- // Collection of Unix tools, comparable to coreutils
- // SPDX-FileCopyrightText: 2017-2022 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only
- #define _POSIX_C_SOURCE 200809L
- #include <stdio.h> /* perror */
- #include <stdlib.h> /* malloc */
- #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;
- if(argc < 2)
- {
- arg_len++;
- }
- for(int i = 1; i < argc; i++)
- {
- arg_len += strlen(argv[i]) + 1; // str + space|newline
- }
- buffer = malloc(arg_len);
- if(buffer == NULL)
- {
- perror("malloc(arg_len)");
- return 1;
- }
- buffer_p = buffer;
- for(int i = 1; i < argc; i++)
- {
- /* flawfinder: ignore, consider that arguments are safely separated by NULL */
- buffer_p = strcpy(buffer_p, argv[i]);
- buffer_p += strlen(buffer_p);
- if(i < argc - 1)
- {
- *buffer_p++ = ' ';
- }
- }
- *buffer_p++ = '\n';
- if(write(1, buffer, arg_len) < (ssize_t)arg_len)
- {
- perror("write(1, buffer, arg_len)");
- err++;
- }
- free(buffer);
- return err;
- }