Skip to content

Instantly share code, notes, and snippets.

@munificent
Created July 20, 2011 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save munificent/1094321 to your computer and use it in GitHub Desktop.
Save munificent/1094321 to your computer and use it in GitHub Desktop.
UNIX V5, OpenBSD, Plan 9, FreeBSD, and GNU coreutils implementations of echo.c
#include <u.h>
#include <libc.h>
void
main(int argc, char *argv[])
{
int noNewline;
int arg, length;
char *output, *p;
/* Check for -n. */
noNewline = 0;
if(argc > 1 && strcmp(argv[1], "-n") == 0) noNewline = 1;
/* Figure out how big of a buffer we need. */
length = 1;
for(arg = 1 + noNewline; arg < argc; arg++) length += strlen(argv[arg]) + 1;
output = malloc(length);
if (output == 0) exits("no memory");
/* Concatenate the remaining arguments. */
p = result;
for (arg = 1 + noNewline; arg < argc; arg++) {
strcpy(p, argv[arg]);
p += strlen(p);
if (arg < argc - 1) *p++ = ' ';
}
if (!noNewline) *p++ = '\n';
/* Write the buffer back out. */
if (write(1, output, p - output) < 0) {
fprint(2, "echo: write error: %r\n");
exits("write error");
}
exits((char *)0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment