Skip to content

Instantly share code, notes, and snippets.

@pete
Last active February 10, 2024 07:12
Show Gist options
  • Save pete/665971 to your computer and use it in GitHub Desktop.
Save pete/665971 to your computer and use it in GitHub Desktop.
Various implementations of the 'cat' command, for comparison.
I turned this gist into a "real" repository. It is here: http://github.com/pete/cats .
Here, placed side-by-side for comparison, are GNU's implementation of
cat, Plan 9's implementation, Busybox's implementation, and NetBSD's
implementation, Seventh Edition Unix (1979), and 4.3BSD.
For good measure (and because I suppose I am now committed to collecting
cats) also included are Second Edition Unix (in assembly) and Inferno's
implementation (in Limbo) for good measure.
All cat.c files (renamed by prefixing the name of the source source) are
presented, unaltered and in their entirety. Note how easy it is to read
and understand plan9-cat.c (it should take less than a couple of minutes
possibly even for coders that don't know C). Other than that, I think
the files speak for themselves.
Keep in mind while reading that the cat utility's purpose is to
concatenate files.
Lastly, here are the line and character counts, sorted:
Lines Chars Filename
---------------------------
35 531 plan9-cat.c
48 955 busybox-cat.c
48 986 inferno-cat.b
63 1130 unix7-cat.c
64 646 unix2-cat.s
222 3948 4.3bsd-cat.c
316 6952 netbsd-cat.c
782 22684 gnu-cat.c
1578 37832 total
/*
* Copyright (c) 1980 Regents of the University of California.
* All rights reserved. The Berkeley software License Agreement
* specifies the terms and conditions for redistribution.
*/
#ifndef lint
static char sccsid[] = "@(#)cat.c 5.2 (Berkeley) 12/6/85";
#endif not lint
/*
* Concatenate files.
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
/* #define OPTSIZE BUFSIZ /* define this only if not 4.2 BSD or beyond */
int bflg, eflg, nflg, sflg, tflg, uflg, vflg;
int spaced, col, lno, inline, ibsize, obsize;
main(argc, argv)
char **argv;
{
int fflg = 0;
register FILE *fi;
register c;
int dev, ino = -1;
struct stat statb;
int retval = 0;
lno = 1;
for( ; argc>1 && argv[1][0]=='-'; argc--,argv++) {
switch(argv[1][1]) {
case 0:
break;
case 'u':
setbuf(stdout, (char *)NULL);
uflg++;
continue;
case 'n':
nflg++;
continue;
case 'b':
bflg++;
nflg++;
continue;
case 'v':
vflg++;
continue;
case 's':
sflg++;
continue;
case 'e':
eflg++;
vflg++;
continue;
case 't':
tflg++;
vflg++;
continue;
}
break;
}
if (fstat(fileno(stdout), &statb) == 0) {
statb.st_mode &= S_IFMT;
if (statb.st_mode!=S_IFCHR && statb.st_mode!=S_IFBLK) {
dev = statb.st_dev;
ino = statb.st_ino;
}
#ifndef OPTSIZE
obsize = statb.st_blksize;
#endif
}
else
obsize = 0;
if (argc < 2) {
argc = 2;
fflg++;
}
while (--argc > 0) {
if (fflg || (*++argv)[0]=='-' && (*argv)[1]=='\0')
fi = stdin;
else {
if ((fi = fopen(*argv, "r")) == NULL) {
perror(*argv);
retval = 1;
continue;
}
}
if (fstat(fileno(fi), &statb) == 0) {
if ((statb.st_mode & S_IFMT) == S_IFREG &&
statb.st_dev==dev && statb.st_ino==ino) {
fprintf(stderr, "cat: input %s is output\n",
fflg?"-": *argv);
fclose(fi);
retval = 1;
continue;
}
#ifndef OPTSIZE
ibsize = statb.st_blksize;
#endif
}
else
ibsize = 0;
if (nflg||sflg||vflg)
copyopt(fi);
else if (uflg) {
while ((c = getc(fi)) != EOF)
putchar(c);
} else
retval |= fastcat(fileno(fi)); /* no flags specified */
if (fi!=stdin)
fclose(fi);
else
clearerr(fi); /* reset sticky eof */
if (ferror(stdout)) {
fprintf(stderr, "cat: output write error\n");
retval = 1;
break;
}
}
exit(retval);
}
copyopt(f)
register FILE *f;
{
register int c;
top:
c = getc(f);
if (c == EOF)
return;
if (c == '\n') {
if (inline == 0) {
if (sflg && spaced)
goto top;
spaced = 1;
}
if (nflg && bflg==0 && inline == 0)
printf("%6d\t", lno++);
if (eflg)
putchar('$');
putchar('\n');
inline = 0;
goto top;
}
if (nflg && inline == 0)
printf("%6d\t", lno++);
inline = 1;
if (vflg) {
if (tflg==0 && c == '\t')
putchar(c);
else {
if (c > 0177) {
printf("M-");
c &= 0177;
}
if (c < ' ')
printf("^%c", c+'@');
else if (c == 0177)
printf("^?");
else
putchar(c);
}
} else
putchar(c);
spaced = 0;
goto top;
}
fastcat(fd)
register int fd;
{
register int buffsize, n, nwritten, offset;
register char *buff;
struct stat statbuff;
char *malloc();
#ifndef OPTSIZE
if (obsize)
buffsize = obsize; /* common case, use output blksize */
else if (ibsize)
buffsize = ibsize;
else
buffsize = BUFSIZ;
#else
buffsize = OPTSIZE;
#endif
if ((buff = malloc(buffsize)) == NULL) {
perror("cat: no memory");
return (1);
}
/*
* Note that on some systems (V7), very large writes to a pipe
* return less than the requested size of the write.
* In this case, multiple writes are required.
*/
while ((n = read(fd, buff, buffsize)) > 0) {
offset = 0;
do {
nwritten = write(fileno(stdout), &buff[offset], n);
if (nwritten <= 0) {
perror("cat: write error");
exit(2);
}
offset += nwritten;
} while ((n -= nwritten) > 0);
}
free(buff);
if (n < 0) {
perror("cat: read error");
return (1);
}
return (0);
}
/* vi: set sw=4 ts=4: */
/*
* cat implementation for busybox
*
* Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* Licensed under GPLv2, see file License in this tarball for details.
*/
/* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cat.html */
#include "libbb.h"
/* This is a NOFORK applet. Be very careful! */
int bb_cat(char **argv)
{
int fd;
int retval = EXIT_SUCCESS;
if (!*argv)
argv = (char**) &bb_argv_dash;
do {
fd = open_or_warn_stdin(*argv);
if (fd >= 0) {
/* This is not a xfunc - never exits */
off_t r = bb_copyfd_eof(fd, STDOUT_FILENO);
if (fd != STDIN_FILENO)
close(fd);
if (r >= 0)
continue;
}
retval = EXIT_FAILURE;
} while (*++argv);
return retval;
}
int cat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cat_main(int argc ATTRIBUTE_UNUSED, char **argv)
{
getopt32(argv, "u");
argv += optind;
return bb_cat(argv);
}
/* cat -- concatenate files and print on the standard output.
Copyright (C) 1988, 1990-1991, 1995-2010 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Differences from the Unix cat:
* Always unbuffered, -u is ignored.
* Usually much faster than other versions of cat, the difference
is especially apparent when using the -v option.
By tege@sics.se, Torbjorn Granlund, advised by rms, Richard Stallman. */
#include <config.h>
#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>
#if HAVE_STROPTS_H
# include <stropts.h>
#endif
#if HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#include "system.h"
#include "error.h"
#include "full-write.h"
#include "quote.h"
#include "safe-read.h"
#include "xfreopen.h"
/* The official name of this program (e.g., no `g' prefix). */
#define PROGRAM_NAME "cat"
#define AUTHORS \
proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
proper_name ("Richard M. Stallman")
/* Name of input file. May be "-". */
static char const *infile;
/* Descriptor on which input file is open. */
static int input_desc;
/* Buffer for line numbers.
An 11 digit counter may overflow within an hour on a P2/466,
an 18 digit counter needs about 1000y */
#define LINE_COUNTER_BUF_LEN 20
static char line_buf[LINE_COUNTER_BUF_LEN] =
{
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0',
'\t', '\0'
};
/* Position in `line_buf' where printing starts. This will not change
unless the number of lines is larger than 999999. */
static char *line_num_print = line_buf + LINE_COUNTER_BUF_LEN - 8;
/* Position of the first digit in `line_buf'. */
static char *line_num_start = line_buf + LINE_COUNTER_BUF_LEN - 3;
/* Position of the last digit in `line_buf'. */
static char *line_num_end = line_buf + LINE_COUNTER_BUF_LEN - 3;
/* Preserves the `cat' function's local `newlines' between invocations. */
static int newlines2 = 0;
void
usage (int status)
{
if (status != EXIT_SUCCESS)
fprintf (stderr, _("Try `%s --help' for more information.\n"),
program_name);
else
{
printf (_("\
Usage: %s [OPTION]... [FILE]...\n\
"),
program_name);
fputs (_("\
Concatenate FILE(s), or standard input, to standard output.\n\
\n\
-A, --show-all equivalent to -vET\n\
-b, --number-nonblank number nonempty output lines\n\
-e equivalent to -vE\n\
-E, --show-ends display $ at end of each line\n\
-n, --number number all output lines\n\
-s, --squeeze-blank suppress repeated empty output lines\n\
"), stdout);
fputs (_("\
-t equivalent to -vT\n\
-T, --show-tabs display TAB characters as ^I\n\
-u (ignored)\n\
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB\n\
"), stdout);
fputs (HELP_OPTION_DESCRIPTION, stdout);
fputs (VERSION_OPTION_DESCRIPTION, stdout);
fputs (_("\
\n\
With no FILE, or when FILE is -, read standard input.\n\
"), stdout);
printf (_("\
\n\
Examples:\n\
%s f - g Output f's contents, then standard input, then g's contents.\n\
%s Copy standard input to standard output.\n\
"),
program_name, program_name);
emit_ancillary_info ();
}
exit (status);
}
/* Compute the next line number. */
static void
next_line_num (void)
{
char *endp = line_num_end;
do
{
if ((*endp)++ < '9')
return;
*endp-- = '0';
}
while (endp >= line_num_start);
if (line_num_start > line_buf)
*--line_num_start = '1';
else
*line_buf = '>';
if (line_num_start < line_num_print)
line_num_print--;
}
/* Plain cat. Copies the file behind `input_desc' to STDOUT_FILENO.
Return true if successful. */
static bool
simple_cat (
/* Pointer to the buffer, used by reads and writes. */
char *buf,
/* Number of characters preferably read or written by each read and write
call. */
size_t bufsize)
{
/* Actual number of characters read, and therefore written. */
size_t n_read;
/* Loop until the end of the file. */
for (;;)
{
/* Read a block of input. */
n_read = safe_read (input_desc, buf, bufsize);
if (n_read == SAFE_READ_ERROR)
{
error (0, errno, "%s", infile);
return false;
}
/* End of this file? */
if (n_read == 0)
return true;
/* Write this block out. */
{
/* The following is ok, since we know that 0 < n_read. */
size_t n = n_read;
if (full_write (STDOUT_FILENO, buf, n) != n)
error (EXIT_FAILURE, errno, _("write error"));
}
}
}
/* Write any pending output to STDOUT_FILENO.
Pending is defined to be the *BPOUT - OUTBUF bytes starting at OUTBUF.
Then set *BPOUT to OUTPUT if it's not already that value. */
static inline void
write_pending (char *outbuf, char **bpout)
{
size_t n_write = *bpout - outbuf;
if (0 < n_write)
{
if (full_write (STDOUT_FILENO, outbuf, n_write) != n_write)
error (EXIT_FAILURE, errno, _("write error"));
*bpout = outbuf;
}
}
/* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
Return true if successful.
Called if any option more than -u was specified.
A newline character is always put at the end of the buffer, to make
an explicit test for buffer end unnecessary. */
static bool
cat (
/* Pointer to the beginning of the input buffer. */
char *inbuf,
/* Number of characters read in each read call. */
size_t insize,
/* Pointer to the beginning of the output buffer. */
char *outbuf,
/* Number of characters written by each write call. */
size_t outsize,
/* Variables that have values according to the specified options. */
bool show_nonprinting,
bool show_tabs,
bool number,
bool number_nonblank,
bool show_ends,
bool squeeze_blank)
{
/* Last character read from the input buffer. */
unsigned char ch;
/* Pointer to the next character in the input buffer. */
char *bpin;
/* Pointer to the first non-valid byte in the input buffer, i.e. the
current end of the buffer. */
char *eob;
/* Pointer to the position where the next character shall be written. */
char *bpout;
/* Number of characters read by the last read call. */
size_t n_read;
/* Determines how many consecutive newlines there have been in the
input. 0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1,
etc. Initially 0 to indicate that we are at the beginning of a
new line. The "state" of the procedure is determined by
NEWLINES. */
int newlines = newlines2;
#ifdef FIONREAD
/* If nonzero, use the FIONREAD ioctl, as an optimization.
(On Ultrix, it is not supported on NFS file systems.) */
bool use_fionread = true;
#endif
/* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
is read immediately. */
eob = inbuf;
bpin = eob + 1;
bpout = outbuf;
for (;;)
{
do
{
/* Write if there are at least OUTSIZE bytes in OUTBUF. */
if (outbuf + outsize <= bpout)
{
char *wp = outbuf;
size_t remaining_bytes;
do
{
if (full_write (STDOUT_FILENO, wp, outsize) != outsize)
error (EXIT_FAILURE, errno, _("write error"));
wp += outsize;
remaining_bytes = bpout - wp;
}
while (outsize <= remaining_bytes);
/* Move the remaining bytes to the beginning of the
buffer. */
memmove (outbuf, wp, remaining_bytes);
bpout = outbuf + remaining_bytes;
}
/* Is INBUF empty? */
if (bpin > eob)
{
bool input_pending = false;
#ifdef FIONREAD
int n_to_read = 0;
/* Is there any input to read immediately?
If not, we are about to wait,
so write all buffered output before waiting. */
if (use_fionread
&& ioctl (input_desc, FIONREAD, &n_to_read) < 0)
{
/* Ultrix returns EOPNOTSUPP on NFS;
HP-UX returns ENOTTY on pipes.
SunOS returns EINVAL and
More/BSD returns ENODEV on special files
like /dev/null.
Irix-5 returns ENOSYS on pipes. */
if (errno == EOPNOTSUPP || errno == ENOTTY
|| errno == EINVAL || errno == ENODEV
|| errno == ENOSYS)
use_fionread = false;
else
{
error (0, errno, _("cannot do ioctl on %s"), quote (infile));
newlines2 = newlines;
return false;
}
}
if (n_to_read != 0)
input_pending = true;
#endif
if (!input_pending)
write_pending (outbuf, &bpout);
/* Read more input into INBUF. */
n_read = safe_read (input_desc, inbuf, insize);
if (n_read == SAFE_READ_ERROR)
{
error (0, errno, "%s", infile);
write_pending (outbuf, &bpout);
newlines2 = newlines;
return false;
}
if (n_read == 0)
{
write_pending (outbuf, &bpout);
newlines2 = newlines;
return true;
}
/* Update the pointers and insert a sentinel at the buffer
end. */
bpin = inbuf;
eob = bpin + n_read;
*eob = '\n';
}
else
{
/* It was a real (not a sentinel) newline. */
/* Was the last line empty?
(i.e. have two or more consecutive newlines been read?) */
if (++newlines > 0)
{
if (newlines >= 2)
{
/* Limit this to 2 here. Otherwise, with lots of
consecutive newlines, the counter could wrap
around at INT_MAX. */
newlines = 2;
/* Are multiple adjacent empty lines to be substituted
by single ditto (-s), and this was the second empty
line? */
if (squeeze_blank)
{
ch = *bpin++;
continue;
}
}
/* Are line numbers to be written at empty lines (-n)? */
if (number && !number_nonblank)
{
next_line_num ();
bpout = stpcpy (bpout, line_num_print);
}
}
/* Output a currency symbol if requested (-e). */
if (show_ends)
*bpout++ = '$';
/* Output the newline. */
*bpout++ = '\n';
}
ch = *bpin++;
}
while (ch == '\n');
/* Are we at the beginning of a line, and line numbers are requested? */
if (newlines >= 0 && number)
{
next_line_num ();
bpout = stpcpy (bpout, line_num_print);
}
/* Here CH cannot contain a newline character. */
/* The loops below continue until a newline character is found,
which means that the buffer is empty or that a proper newline
has been found. */
/* If quoting, i.e. at least one of -v, -e, or -t specified,
scan for chars that need conversion. */
if (show_nonprinting)
{
for (;;)
{
if (ch >= 32)
{
if (ch < 127)
*bpout++ = ch;
else if (ch == 127)
{
*bpout++ = '^';
*bpout++ = '?';
}
else
{
*bpout++ = 'M';
*bpout++ = '-';
if (ch >= 128 + 32)
{
if (ch < 128 + 127)
*bpout++ = ch - 128;
else
{
*bpout++ = '^';
*bpout++ = '?';
}
}
else
{
*bpout++ = '^';
*bpout++ = ch - 128 + 64;
}
}
}
else if (ch == '\t' && !show_tabs)
*bpout++ = '\t';
else if (ch == '\n')
{
newlines = -1;
break;
}
else
{
*bpout++ = '^';
*bpout++ = ch + 64;
}
ch = *bpin++;
}
}
else
{
/* Not quoting, neither of -v, -e, or -t specified. */
for (;;)
{
if (ch == '\t' && show_tabs)
{
*bpout++ = '^';
*bpout++ = ch + 64;
}
else if (ch != '\n')
*bpout++ = ch;
else
{
newlines = -1;
break;
}
ch = *bpin++;
}
}
}
}
int
main (int argc, char **argv)
{
/* Optimal size of i/o operations of output. */
size_t outsize;
/* Optimal size of i/o operations of input. */
size_t insize;
size_t page_size = getpagesize ();
/* Pointer to the input buffer. */
char *inbuf;
/* Pointer to the output buffer. */
char *outbuf;
bool ok = true;
int c;
/* Index in argv to processed argument. */
int argind;
/* Device number of the output (file or whatever). */
dev_t out_dev;
/* I-node number of the output. */
ino_t out_ino;
/* True if the output file should not be the same as any input file. */
bool check_redirection = true;
/* Nonzero if we have ever read standard input. */
bool have_read_stdin = false;
struct stat stat_buf;
/* Variables that are set according to the specified options. */
bool number = false;
bool number_nonblank = false;
bool squeeze_blank = false;
bool show_ends = false;
bool show_nonprinting = false;
bool show_tabs = false;
int file_open_mode = O_RDONLY;
static struct option const long_options[] =
{
{"number-nonblank", no_argument, NULL, 'b'},
{"number", no_argument, NULL, 'n'},
{"squeeze-blank", no_argument, NULL, 's'},
{"show-nonprinting", no_argument, NULL, 'v'},
{"show-ends", no_argument, NULL, 'E'},
{"show-tabs", no_argument, NULL, 'T'},
{"show-all", no_argument, NULL, 'A'},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0}
};
initialize_main (&argc, &argv);
set_program_name (argv[0]);
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
/* Arrange to close stdout if we exit via the
case_GETOPT_HELP_CHAR or case_GETOPT_VERSION_CHAR code.
Normally STDOUT_FILENO is used rather than stdout, so
close_stdout does nothing. */
atexit (close_stdout);
/* Parse command line options. */
while ((c = getopt_long (argc, argv, "benstuvAET", long_options, NULL))
!= -1)
{
switch (c)
{
case 'b':
number = true;
number_nonblank = true;
break;
case 'e':
show_ends = true;
show_nonprinting = true;
break;
case 'n':
number = true;
break;
case 's':
squeeze_blank = true;
break;
case 't':
show_tabs = true;
show_nonprinting = true;
break;
case 'u':
/* We provide the -u feature unconditionally. */
break;
case 'v':
show_nonprinting = true;
break;
case 'A':
show_nonprinting = true;
show_ends = true;
show_tabs = true;
break;
case 'E':
show_ends = true;
break;
case 'T':
show_tabs = true;
break;
case_GETOPT_HELP_CHAR;
case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
default:
usage (EXIT_FAILURE);
}
}
/* Get device, i-node number, and optimal blocksize of output. */
if (fstat (STDOUT_FILENO, &stat_buf) < 0)
error (EXIT_FAILURE, errno, _("standard output"));
outsize = io_blksize (stat_buf);
/* Input file can be output file for non-regular files.
fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
on others, so the checking should not be done for those types,
and to allow things like cat < /dev/tty > /dev/tty, checking
is not done for device files either. */
if (S_ISREG (stat_buf.st_mode))
{
out_dev = stat_buf.st_dev;
out_ino = stat_buf.st_ino;
}
else
{
check_redirection = false;
#ifdef lint /* Suppress `used before initialized' warning. */
out_dev = 0;
out_ino = 0;
#endif
}
if (! (number || show_ends || squeeze_blank))
{
file_open_mode |= O_BINARY;
if (O_BINARY && ! isatty (STDOUT_FILENO))
xfreopen (NULL, "wb", stdout);
}
/* Check if any of the input files are the same as the output file. */
/* Main loop. */
infile = "-";
argind = optind;
do
{
if (argind < argc)
infile = argv[argind];
if (STREQ (infile, "-"))
{
have_read_stdin = true;
input_desc = STDIN_FILENO;
if ((file_open_mode & O_BINARY) && ! isatty (STDIN_FILENO))
xfreopen (NULL, "rb", stdin);
}
else
{
input_desc = open (infile, file_open_mode);
if (input_desc < 0)
{
error (0, errno, "%s", infile);
ok = false;
continue;
}
}
if (fstat (input_desc, &stat_buf) < 0)
{
error (0, errno, "%s", infile);
ok = false;
goto contin;
}
insize = io_blksize (stat_buf);
/* Compare the device and i-node numbers of this input file with
the corresponding values of the (output file associated with)
stdout, and skip this input file if they coincide. Input
files cannot be redirected to themselves. */
if (check_redirection
&& stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino
&& (input_desc != STDIN_FILENO))
{
error (0, 0, _("%s: input file is output file"), infile);
ok = false;
goto contin;
}
/* Select which version of `cat' to use. If any format-oriented
options were given use `cat'; otherwise use `simple_cat'. */
if (! (number || show_ends || show_nonprinting
|| show_tabs || squeeze_blank))
{
insize = MAX (insize, outsize);
inbuf = xmalloc (insize + page_size - 1);
ok &= simple_cat (ptr_align (inbuf, page_size), insize);
}
else
{
inbuf = xmalloc (insize + 1 + page_size - 1);
/* Why are
(OUTSIZE - 1 + INSIZE * 4 + LINE_COUNTER_BUF_LEN + PAGE_SIZE - 1)
bytes allocated for the output buffer?
A test whether output needs to be written is done when the input
buffer empties or when a newline appears in the input. After
output is written, at most (OUTSIZE - 1) bytes will remain in the
buffer. Now INSIZE bytes of input is read. Each input character
may grow by a factor of 4 (by the prepending of M-^). If all
characters do, and no newlines appear in this block of input, we
will have at most (OUTSIZE - 1 + INSIZE * 4) bytes in the buffer.
If the last character in the preceding block of input was a
newline, a line number may be written (according to the given
options) as the first thing in the output buffer. (Done after the
new input is read, but before processing of the input begins.)
A line number requires seldom more than LINE_COUNTER_BUF_LEN
positions.
Align the output buffer to a page size boundary, for efficency on
some paging implementations, so add PAGE_SIZE - 1 bytes to the
request to make room for the alignment. */
outbuf = xmalloc (outsize - 1 + insize * 4 + LINE_COUNTER_BUF_LEN
+ page_size - 1);
ok &= cat (ptr_align (inbuf, page_size), insize,
ptr_align (outbuf, page_size), outsize, show_nonprinting,
show_tabs, number, number_nonblank, show_ends,
squeeze_blank);
free (outbuf);
}
free (inbuf);
contin:
if (!STREQ (infile, "-") && close (input_desc) < 0)
{
error (0, errno, "%s", infile);
ok = false;
}
}
while (++argind < argc);
if (have_read_stdin && close (STDIN_FILENO) < 0)
error (EXIT_FAILURE, errno, _("closing standard input"));
exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
}
implement Cat;
include "sys.m";
sys: Sys;
include "draw.m";
Cat: module
{
init: fn(ctxt: ref Draw->Context, argv: list of string);
};
stdout: ref Sys->FD;
init(nil: ref Draw->Context, args: list of string)
{
sys = load Sys Sys->PATH;
stdout = sys->fildes(1);
args = tl args;
if(args == nil)
args = "-" :: nil;
for(; args != nil; args = tl args){
file := hd args;
if(file != "-"){
fd := sys->open(file, Sys->OREAD);
if(fd == nil){
sys->fprint(sys->fildes(2), "cat: cannot open %s: %r\n", file);
raise "fail:bad open";
}
cat(fd, file);
}else
cat(sys->fildes(0), "<stdin>");
}
}
cat(fd: ref Sys->FD, file: string)
{
buf := array[Sys->ATOMICIO] of byte;
while((n := sys->read(fd, buf, len buf)) > 0)
if(sys->write(stdout, buf, n) < n) {
sys->fprint(sys->fildes(2), "cat: write error: %r\n");
raise "fail:write error";
}
if(n < 0) {
sys->fprint(sys->fildes(2), "cat: error reading %s: %r\n", file);
raise "fail:read error";
}
}
/* $NetBSD: cat.c,v 1.47 2008/07/20 00:52:39 lukem Exp $ */
/*
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Kevin Fall.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if HAVE_NBTOOL_CONFIG_H
#include "nbtool_config.h"
#endif
#include <sys/cdefs.h>
#if !defined(lint)
__COPYRIGHT(
"@(#) Copyright (c) 1989, 1993\
The Regents of the University of California. All rights reserved.");
#if 0
static char sccsid[] = "@(#)cat.c 8.2 (Berkeley) 4/27/95";
#else
__RCSID("$NetBSD: cat.c,v 1.47 2008/07/20 00:52:39 lukem Exp $");
#endif
#endif /* not lint */
#include <sys/param.h>
#include <sys/stat.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int bflag, eflag, fflag, lflag, nflag, sflag, tflag, vflag;
int rval;
const char *filename;
int main(int, char *[]);
void cook_args(char *argv[]);
void cook_buf(FILE *);
void raw_args(char *argv[]);
void raw_cat(int);
int
main(int argc, char *argv[])
{
int ch;
struct flock stdout_lock;
setprogname(argv[0]);
(void)setlocale(LC_ALL, "");
while ((ch = getopt(argc, argv, "beflnstuv")) != -1)
switch (ch) {
case 'b':
bflag = nflag = 1; /* -b implies -n */
break;
case 'e':
eflag = vflag = 1; /* -e implies -v */
break;
case 'f':
fflag = 1;
break;
case 'l':
lflag = 1;
break;
case 'n':
nflag = 1;
break;
case 's':
sflag = 1;
break;
case 't':
tflag = vflag = 1; /* -t implies -v */
break;
case 'u':
setbuf(stdout, NULL);
break;
case 'v':
vflag = 1;
break;
default:
case '?':
(void)fprintf(stderr,
"usage: cat [-beflnstuv] [-] [file ...]\n");
exit(EXIT_FAILURE);
/* NOTREACHED */
}
argv += optind;
if (lflag) {
stdout_lock.l_len = 0;
stdout_lock.l_start = 0;
stdout_lock.l_type = F_WRLCK;
stdout_lock.l_whence = SEEK_SET;
if (fcntl(STDOUT_FILENO, F_SETLKW, &stdout_lock) == -1)
err(EXIT_FAILURE, "stdout");
}
if (bflag || eflag || nflag || sflag || tflag || vflag)
cook_args(argv);
else
raw_args(argv);
if (fclose(stdout))
err(EXIT_FAILURE, "stdout");
return (rval);
}
void
cook_args(char **argv)
{
FILE *fp;
fp = stdin;
filename = "stdin";
do {
if (*argv) {
if (!strcmp(*argv, "-"))
fp = stdin;
else if ((fp = fopen(*argv,
fflag ? "rf" : "r")) == NULL) {
warn("%s", *argv);
rval = EXIT_FAILURE;
++argv;
continue;
}
filename = *argv++;
}
cook_buf(fp);
if (fp != stdin)
(void)fclose(fp);
else
clearerr(fp);
} while (*argv);
}
void
cook_buf(FILE *fp)
{
int ch, gobble, line, prev;
line = gobble = 0;
for (prev = '\n'; (ch = getc(fp)) != EOF; prev = ch) {
if (prev == '\n') {
if (ch == '\n') {
if (sflag) {
if (!gobble && nflag && !bflag)
(void)fprintf(stdout,
"%6d\t\n", ++line);
else if (!gobble && putchar(ch) == EOF)
break;
gobble = 1;
continue;
}
if (nflag) {
if (!bflag) {
(void)fprintf(stdout,
"%6d\t", ++line);
if (ferror(stdout))
break;
} else if (eflag) {
(void)fprintf(stdout,
"%6s\t", "");
if (ferror(stdout))
break;
}
}
} else if (nflag) {
(void)fprintf(stdout, "%6d\t", ++line);
if (ferror(stdout))
break;
}
}
gobble = 0;
if (ch == '\n') {
if (eflag)
if (putchar('$') == EOF)
break;
} else if (ch == '\t') {
if (tflag) {
if (putchar('^') == EOF || putchar('I') == EOF)
break;
continue;
}
} else if (vflag) {
if (!isascii(ch)) {
if (putchar('M') == EOF || putchar('-') == EOF)
break;
ch = toascii(ch);
}
if (iscntrl(ch)) {
if (putchar('^') == EOF ||
putchar(ch == '\177' ? '?' :
ch | 0100) == EOF)
break;
continue;
}
}
if (putchar(ch) == EOF)
break;
}
if (ferror(fp)) {
warn("%s", filename);
rval = EXIT_FAILURE;
clearerr(fp);
}
if (ferror(stdout))
err(EXIT_FAILURE, "stdout");
}
void
raw_args(char **argv)
{
int fd;
fd = fileno(stdin);
filename = "stdin";
do {
if (*argv) {
if (!strcmp(*argv, "-"))
fd = fileno(stdin);
else if (fflag) {
struct stat st;
fd = open(*argv, O_RDONLY|O_NONBLOCK, 0);
if (fd < 0)
goto skip;
if (fstat(fd, &st) == -1) {
close(fd);
goto skip;
}
if (!S_ISREG(st.st_mode)) {
close(fd);
warnx("%s: not a regular file", *argv);
goto skipnomsg;
}
}
else if ((fd = open(*argv, O_RDONLY, 0)) < 0) {
skip:
warn("%s", *argv);
skipnomsg:
rval = EXIT_FAILURE;
++argv;
continue;
}
filename = *argv++;
}
raw_cat(fd);
if (fd != fileno(stdin))
(void)close(fd);
} while (*argv);
}
void
raw_cat(int rfd)
{
static char *buf;
static char fb_buf[BUFSIZ];
static size_t bsize;
ssize_t nr, nw, off;
int wfd;
wfd = fileno(stdout);
if (buf == NULL) {
struct stat sbuf;
if (fstat(wfd, &sbuf) == 0 &&
sbuf.st_blksize > sizeof(fb_buf)) {
bsize = sbuf.st_blksize;
buf = malloc(bsize);
}
if (buf == NULL) {
bsize = sizeof(fb_buf);
buf = fb_buf;
}
}
while ((nr = read(rfd, buf, bsize)) > 0)
for (off = 0; nr; nr -= nw, off += nw)
if ((nw = write(wfd, buf + off, (size_t)nr)) < 0)
err(EXIT_FAILURE, "stdout");
if (nr < 0) {
warn("%s", filename);
rval = EXIT_FAILURE;
}
}
#include <u.h>
#include <libc.h>
void
cat(int f, char *s)
{
char buf[8192];
long n;
while((n=read(f, buf, (long)sizeof buf))>0)
if(write(1, buf, n)!=n)
sysfatal("write error copying %s: %r", s);
if(n < 0)
sysfatal("error reading %s: %r", s);
}
void
main(int argc, char *argv[])
{
int f, i;
argv0 = "cat";
if(argc == 1)
cat(0, "<stdin>");
else for(i=1; i<argc; i++){
f = open(argv[i], OREAD);
if(f < 0)
sysfatal("can't open %s: %r", argv[i]);
else{
cat(f, argv[i]);
close(f);
}
}
exits(0);
}
/ cat -- concatinate files
mov (sp)+,r5
tst (sp)+
mov $obuf,r2
cmp r5,$1
beq 3f
loop:
dec r5
ble done
mov (sp)+,r0
cmpb (r0),$'-
bne 2f
clr fin
br 3f
2:
mov r0,0f
sys open; 0:..; 0
bes loop
mov r0,fin
3:
mov fin,r0
sys read; ibuf; 512.
bes 3f
mov r0,r4
beq 3f
mov $ibuf,r3
4:
movb (r3)+,r0
jsr pc,putc
dec r4
bne 4b
br 3b
3:
mov fin,r0
beq loop
sys close
br loop
done:
sub $obuf,r2
beq 1f
mov r2,0f
mov $1,r0
sys write; obuf; 0:..
1:
sys exit
putc:
movb r0,(r2)+
cmp r2,$obuf+512.
blo 1f
mov $1,r0
sys write; obuf; 512.
mov $obuf,r2
1:
rts pc
.bss
ibuf: .=.+512.
obuf: .=.+512.
fin: .=.+2
.text
/*
* Concatenate files.
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
char stdbuf[BUFSIZ];
main(argc, argv)
char **argv;
{
int fflg = 0;
register FILE *fi;
register c;
int dev, ino = -1;
struct stat statb;
setbuf(stdout, stdbuf);
for( ; argc>1 && argv[1][0]=='-'; argc--,argv++) {
switch(argv[1][1]) {
case 0:
break;
case 'u':
setbuf(stdout, (char *)NULL);
continue;
}
break;
}
fstat(fileno(stdout), &statb);
statb.st_mode &= S_IFMT;
if (statb.st_mode!=S_IFCHR && statb.st_mode!=S_IFBLK) {
dev = statb.st_dev;
ino = statb.st_ino;
}
if (argc < 2) {
argc = 2;
fflg++;
}
while (--argc > 0) {
if (fflg || (*++argv)[0]=='-' && (*argv)[1]=='\0')
fi = stdin;
else {
if ((fi = fopen(*argv, "r")) == NULL) {
fprintf(stderr, "cat: can't open %s\n", *argv);
continue;
}
}
fstat(fileno(fi), &statb);
if (statb.st_dev==dev && statb.st_ino==ino) {
fprintf(stderr, "cat: input %s is output\n",
fflg?"-": *argv);
fclose(fi);
continue;
}
while ((c = getc(fi)) != EOF)
putchar(c);
if (fi!=stdin)
fclose(fi);
}
return(0);
}
@Neuromatic
Copy link

busybox ftw

@dcat
Copy link

dcat commented Oct 30, 2014

it never ceases to amaze me how badly GNU manages to fsck up simple software like this.

@OlliV
Copy link

OlliV commented Feb 22, 2015

Hail BSD

@bear8642
Copy link

bear8642 commented Apr 4, 2016

The simplicity of Plan9's source code really shouldn't be able to compete with the rest of these.

@samsonl
Copy link

samsonl commented Oct 4, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment