Name: Anonymous 2015-02-23 16:31
Most elegant solution wins
reference bloated cats: https://gist.github.com/pete/665971
reference bloated cats: https://gist.github.com/pete/665971
#!/usr/bin/perl
use strict;
while(<>){
print $_;
}
#!/bin/env node
/* echo */
console.log(process.argv.slice(2).join(" "))
#!/bin/env node
/* cat */
if (f = process.argv[2]) process.stdout.write(require("fs").readFileSync(f, "utf8"))
else process.stdin.pipe(process.stdout)
#include <stdio.h>
int main() {
puts("MEOW MEOW, MOTHERFUCKER!");
return 0;
}
//cmp.c https://gist.github.com/FrozenVoid/363b9098196d3173ab0c
#include "..\void.h"
//https://gist.github.com/FrozenVoid/87e6ad6212ac9ce496e0
STDSTART
#define HELPCMP "Use as: cmp File1 File2"
if(argc<3)quit(HELPCMP);
u8 asize=filesize(argv[1]);
u8 bsize=filesize(argv[2]);
if(asize==0)quit(HELPCMP);
if(bsize==0)quit(HELPCMP);
if(asize!=bsize){p(argv[1],"is ",(asize>bsize)?asize-bsize:bsize-asize," bytes",(asize>bsize)?"longer":"shorter");exit(EXIT_FAILURE);}
u1 ac,bc;
FILE* a=fopen(argv[1],"rb");
FILE* b=fopen(argv[2],"rb");
if((!a)||(!b)){quit(HELPCMP);}
while(!feof(a)){ac=getc(a);bc=getc(b);
if(ac!=bc)quit("Difference at byte:",ftell(a),"\nFile:",argv[1],":",(ac),"\nFile:",argv[2],":",(bc));;}
puts("Files are identical");
STDEND
#include <unistd.h>
int main(int argc, char** argv) {
argv[0] = "/sbin/ping";
execv(argv[0], argv);
return 0;
}
(defvars((c1p,species,alloca(256)),(c1,yes)))Not LISPy at all.
#![crate_name = "cat"]
#![feature(collections, core, old_io, old_path, rustc_private)]
#![feature(box_syntax, unsafe_destructor)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: cat (GNU coreutils) 8.13 */
extern crate getopts;
use std::old_io::{print, File};
use std::old_io::stdio::{stdout_raw, stdin_raw, stderr};
use std::old_io::{IoResult};
use std::ptr::{copy_nonoverlapping_memory};
pub fn uumain(args: Vec<String>) -> i32 {
let program = &args[0];
let opts = [
getopts::optflag("A", "show-all", "equivalent to -vET"),
getopts::optflag("b", "number-nonblank",
"number nonempty output lines, overrides -n"),
getopts::optflag("e", "", "equivalent to -vE"),
getopts::optflag("E", "show-ends", "display $ at end of each line"),
getopts::optflag("n", "number", "number all output lines"),
getopts::optflag("s", "squeeze-blank", "suppress repeated empty output lines"),
getopts::optflag("t", "", "equivalent to -vT"),
getopts::optflag("T", "show-tabs", "display TAB characters as ^I"),
getopts::optflag("v", "show-nonprinting",
"use ^ and M- notation, except for LF (\\n) and TAB (\\t)"),
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) => m,
Err(f) => panic!("Invalid options\n{}", f)
};
if matches.opt_present("help") {
println!("cat 1.0.0");
println!("");
println!("Usage:");
println!(" {0} [OPTION]... [FILE]...", program);
println!("");
print(&getopts::usage("Concatenate FILE(s), or standard input, to \
standard output.", &opts)[..]);
println!("");
println!("With no FILE, or when FILE is -, read standard input.");
return 0;
}
if matches.opt_present("version") {
println!("cat 1.0.0");
return 0;
}
let mut number_mode = NumberingMode::NumberNone;
if matches.opt_present("n") {
number_mode = NumberingMode::NumberAll;
}
if matches.opt_present("b") {
number_mode = NumberingMode::NumberNonEmpty;
}
let show_nonprint = matches.opts_present(&["A".to_string(), "e".to_string(),
"t".to_string(), "v".to_string()]);
let show_ends = matches.opts_present(&["E".to_string(), "A".to_string(),
"e".to_string()]);
let show_tabs = matches.opts_present(&["A".to_string(), "T".to_string(),
"t".to_string()]);
let squeeze_blank = matches.opt_present("s");
let mut files = matches.free;
if files.is_empty() {
files.push("-".to_string());
}
exec(files, number_mode, show_nonprint, show_ends, show_tabs, squeeze_blank);
0
}
#[derive(Eq, PartialEq)]
enum NumberingMode {
NumberNone,
NumberNonEmpty,
NumberAll,
}
fn write_lines(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
show_ends: bool) {
let mut line_counter: usize = 1;
for (mut reader, interactive) in files.iter().filter_map(|p| open(&p[..])) {
let mut in_buf = [0; 1024 * 31];
let mut out_buf = [0; 1024 * 64];
let mut writer = UnsafeWriter::new(out_buf.as_mut_slice(), stdout_raw());
let mut at_line_start = true;
while let Ok(n) = reader.read(&mut in_buf) {
if n == 0 { break }
let in_buf = &in_buf[..n];
let mut buf_pos = range(0, n);
loop {
writer.possibly_flush();
let pos = match buf_pos.next() {
Some(p) => p,
None => break,
};
if in_buf[pos] == '\n' as u8 {
if !at_line_start || !squeeze_blank {
if at_line_start && number == NumberingMode::NumberAll {
(write!(&mut writer, "{0:6}\t", line_counter)).unwrap();
line_counter += 1;
}
if show_ends {
writer.write_u8('$' as u8).unwrap();
}
writer.write_u8('\n' as u8).unwrap();
if interactive {
writer.flush().unwrap();
}
}
at_line_start = true;
continue;
}
if at_line_start && number != NumberingMode::NumberNone {
(write!(&mut writer, "{0:6}\t", line_counter)).unwrap();
line_counter += 1;
}
match in_buf[pos..].iter().position(|c| *c == '\n' as u8) {
Some(p) => {
writer.write_all(&in_buf[pos..pos + p]).unwrap();
if show_ends {
writer.write_u8('$' as u8).unwrap();
}
writer.write_u8('\n' as u8).unwrap();
if interactive {
writer.flush().unwrap();
}
buf_pos = range(pos + p + 1, n);
at_line_start = true;
},
None => {
writer.write_all(&in_buf[pos..]).unwrap();
at_line_start = false;
break;
}
};
}
}
}
}
fn write_bytes(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
show_ends: bool, show_nonprint: bool, show_tabs: bool) {
let mut line_counter: usize = 1;
for (mut reader, interactive) in files.iter().filter_map(|p| open(&p[..])) {
// Flush all 1024 iterations.
let mut flush_counter = range(0usize, 1024);
let mut in_buf = [0; 1024 * 32];
let mut out_buf = [0; 1024 * 64];
let mut writer = UnsafeWriter::new(out_buf.as_mut_slice(), stdout_raw());
let mut at_line_start = true;
while let Ok(n) = reader.read(&mut in_buf) {
if n == 0 { break }
for &byte in in_buf[..n].iter() {
if flush_counter.next().is_none() {
writer.possibly_flush();
flush_counter = range(0usize, 1024);
}
if byte == '\n' as u8 {
if !at_line_start || !squeeze_blank {
if at_line_start && number == NumberingMode::NumberAll {
(write!(&mut writer, "{0:6}\t", line_counter)).unwrap();
line_counter += 1;
}
if show_ends {
writer.write_u8('$' as u8).unwrap();
}
writer.write_u8('\n' as u8).unwrap();
if interactive {
writer.flush().unwrap();
}
}
at_line_start = true;
continue;
}
if at_line_start && number != NumberingMode::NumberNone {
(write!(&mut writer, "{0:6}\t", line_counter)).unwrap();
line_counter += 1;
at_line_start = false;
}
// This code is slow because of the many branches. cat in glibc avoids
// this by having the whole loop inside show_nonprint.
if byte == '\t' as u8 {
if show_tabs {
writer.write_str("^I")
} else {
writer.write_u8(byte)
}
} else if show_nonprint {
let byte = match byte {
128 ... 255 => {
writer.write_str("M-").unwrap();
byte - 128
},
_ => byte,
};
match byte {
0 ... 31 => writer.write_all(&['^' as u8, byte + 64]),
127 => writer.write_all(&['^' as u8, byte - 64]),
_ => writer.write_u8(byte),
}
} else {
writer.write_u8(byte)
}.unwrap();
}
}
}
}
fn write_fast(files: Vec<String>) {
let mut writer = stdout_raw();
let mut in_buf = [0; 1024 * 64];
for (mut reader, _) in files.iter().filter_map(|p| open(&p[..])) {
while let Ok(n) = reader.read(&mut in_buf) {
if n == 0 { break }
// This interface is completely broken.
writer.write_all(&in_buf[..n]).unwrap();
}
}
}
fn exec(files: Vec<String>, number: NumberingMode, show_nonprint: bool,
show_ends: bool, show_tabs: bool, squeeze_blank: bool) {
if show_nonprint || show_tabs {
write_bytes(files, number, squeeze_blank, show_ends, show_nonprint, show_tabs);
} else if number != NumberingMode::NumberNone || squeeze_blank || show_ends {
write_lines(files, number, squeeze_blank, show_ends);
} else {
write_fast(files);
}
}
fn open(path: &str) -> Option<(Box<Reader>, bool)> {
if path == "-" {
let stdin = stdin_raw();
let interactive = stdin.isatty();
return Some((box stdin as Box<Reader>, interactive));
}
match File::open(&std::old_path::Path::new(path)) {
Ok(f) => Some((box f as Box<Reader>, false)),
Err(e) => {
(writeln!(&mut stderr(), "cat: {0}: {1}", path, e.to_string())).unwrap();
None
},
}
}
struct UnsafeWriter<'a, W> {
inner: W,
buf: &'a mut [u8],
pos: usize,
threshold: usize,
}
impl<'a, W: Writer> UnsafeWriter<'a, W> {
fn new(buf: &'a mut [u8], inner: W) -> UnsafeWriter<'a, W> {
let threshold = buf.len()/2;
UnsafeWriter {
inner: inner,
buf: buf,
pos: 0,
threshold: threshold,
}
}
fn flush_buf(&mut self) -> IoResult<()> {
if self.pos != 0 {
let ret = self.inner.write_all(&self.buf[..self.pos]);
self.pos = 0;
ret
} else {
Ok(())
}
}
fn possibly_flush(&mut self) {
if self.pos > self.threshold {
self.inner.write_all(&self.buf[..self.pos]).unwrap();
self.pos = 0;
}
}
}
#[inline(never)]
fn fail() -> ! {
panic!("assertion failed");
}
impl<'a, W: Writer> Writer for UnsafeWriter<'a, W> {
fn write_all(&mut self, buf: &[u8]) -> IoResult<()> {
let dst = &mut self.buf[self.pos..];
if buf.len() > dst.len() {
fail();
}
unsafe {
copy_nonoverlapping_memory(dst.as_mut_ptr(), buf.as_ptr(), buf.len())
}
self.pos += buf.len();
Ok(())
}
fn flush(&mut self) -> IoResult<()> {
self.flush_buf().and_then(|()| self.inner.flush())
}
}
#[unsafe_destructor]
impl<'a, W: Writer> Drop for UnsafeWriter<'a, W> {
fn drop(&mut self) {
let _ = self.flush_buf();
}
}
/* vim: set ai ts=4 sw=4 sts=4 et : */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
// character-by-character concatination, in case the file is a terminal
void tty_cat(FILE *fp){
int c;
c = fgetc(fp);
while (!feof(fp)){
fputc(c, stdout);
c = fgetc(fp);
}
}
// read files by blocks to play nicer with syscalls and disk reads
void file_cat(FILE *fp){
size_t n_read;
uint8_t *buf = malloc(0x1000);
if (buf){
n_read = fread(buf, 1, 0x1000, fp);
while(n_read){
fwrite(buf, 1, n_read, stdout);
n_read = fread(buf, 1, 0x1000, fp);
}
}
}
void cat_thing(FILE *fp){
if (isatty(fileno(fp))){
tty_cat(fp);
} else {
file_cat(fp);
}
}
void print_help(){
printf(
"Usage: cat [OPTION] ... [FILE] ...\n"
" --help Show this help and exit\n"
" --version Output version information and exit\n"
);
}
int main(int argc, char *argv[]){
unsigned i;
if (argc > 1){
for (i = 1; i < argc; i++){
FILE *fp;
if (strcmp(argv[i], "-") == 0){
fp = stdin;
} else if (strcmp(argv[i], "--help") == 0){
print_help();
exit(0);
} else if (strcmp(argv[i], "--version") == 0){
printf("( =^'.'^=) meow\n");
exit(0);
} else {
fp = fopen(argv[i], "r");
}
if (!fp){
perror(argv[i]);
exit(1);
}
cat_thing(fp);
}
} else {
cat_thing(stdin);
}
return 0;
}
#include <u.h>
#include <libc.h>
static void slurp(int);
void
main(int argc, char **argv)
{
int *fd, i, x;
fd = malloc(sizeof(int) * argc);
if(fd == nil)
exits("No mem");
fd[0] = 0;
if(argc > 1){
argc--;
for(i = 0; argc - i != 0; i++)
fd[i] = open(argv[i], OREAD);
}else{
i = 1;
}
for(x = 0; x < i; x++)
slurp(fd[x]);
}
static void
slup(int x)
{
char buf[512];
int n;
if(x >= 0){
do{
n = read(x, buf, 512);
if(n > 0)
write(1, buf, n);
}while(n > 0);
}
}
import autism
autism.unix_cat()
. ,.
T."-._..---.._,-"/|
l|"-. _.v._ (" |
[l /.'_ \; _~"-.`-t
Y " _(o} _{o)._ ^.|
j T ,-<v>-. T ]
\ l ( /-^-\ ) ! !
\. \. "~" ./ /c-..,__
^r- .._ .- .-" `- . ~"--.
> \. \
] ^. \
3 . "> . Y -System V
,.__.--._ _j \ ~ . ; |
( ~"-._~"^._\ ^. ^._ I . l
"-._ ___ ~"-,_7 .Z-._ 7" Y ; \ _
/" "~-(r r _/_--._~-/ / /,.--^-._ / Y
"-._ '"~~~>-._~]>--^---./____,.^~ ^.^ !
~--._ ' Y---. \./
~~--._ l_ ) \
~-._~~~---._,____..--- \
~----"~ \
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "text.h"
#include "util.h"
static void
usage(void)
{
eprintf("usage: %s [-u] [file ...]\n", argv0);
}
int
main(int argc, char *argv[])
{
FILE *fp;
int ret = 0;
ARGBEGIN {
case 'u':
setbuf(stdout, NULL);
break;
default:
usage();
} ARGEND;
if (!argc) {
concat(stdin, "<stdin>", stdout, "<stdout>");
} else {
for (; *argv; argc--, argv++) {
if (!strcmp(*argv, "-")) {
*argv = "<stdin>";
fp = stdin;
} else if (!(fp = fopen(*argv, "r"))) {
weprintf("fopen %s:", *argv);
ret = 1;
continue;
}
concat(fp, *argv, stdout, "<stdout>");
if (fp != stdin && fshut(fp, *argv))
ret = 1;
}
}
ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>");
return ret;
}
#include <stdio.h>
void cat(FILE *f, char *s)
{
int c;
while ((c = getc(f)) != EOF)
if (putc(c, stdout) == EOF)
fprintf(stderr, "error copying %s\n", s);
if (ferror(f))
fprintf(stderr, "error reading %s\n", s);
}
int main(int argc, char *argv[])
{
FILE *f;
int i;
if (argc == 1)
cat(stdin, "<stdin>");
else for (i = 1; i < argc; i++)
if ((f = fopen(argv[i], "r")) == NULL)
fprintf(stderr, "can't open %s\n", argv[i]);
else {
cat(f, argv[i]);
fclose(f);
}
return 0;
}
#include "..\void.h"the poor fuck doesn't understand include paths
while(!feof(catfile))the poor fuck doesn't understand feof/ferror
#define STDSTART int main(int argc,char** argv){ rng8fastseed();;netstart;the poor fuck does a lot of stupid shit
#define STDEND ; WSACleanup();return EXIT_SUCCESS;}
cat
:/* @cat.c */
/* NOTE: GNU's cat will not cat a file into itself. Should we check for this?
Possibility of infinite loop here. POSIX doesn't specify what happens if
standard input happens to be standard output (cat to temp. file and then
write that to the output? don't write what was already written?) */
#include <errno.h>
#include <stdio.h>
#include <string.h>
#define CATBUF_SIZE 65536 /* increase this if you want OMG MOAR SPEED! */
char catbuf[CATBUF_SIZE];
int main(int argc, char** argv) {
int uflag = 0, retval = 0, i = 1;
FILE *input;
if(argc>1 && !strcmp(*argv,"-u")) {
uflag=1;
retval=setvbuf(stdout,NULL,_IONBF,0);
i++;
}
if(i>=argc) { /* catting stdin */
input=stdin;
goto cat_stdin;
}
while(argv[i]) {
int l;
if(strcmp(argv[i],"-")) {
if(!(input=fopen(argv[i++],"rb"))) {
fprintf(stderr,"%s: could not open %s: %s\n",argv[0],argv[i-1],strerror(errno));
retval=1;
continue;
}
} else {
input=stdin;
i++;
}
cat_stdin:
if(uflag)
retval|=setvbuf(input, NULL, _IONBF, 0);
while(l=fread(catbuf,1,CATBUF_SIZE,input)) {
if(fwrite(catbuf,1,l,stdout)!=l) {
fprintf(stderr,"%s: error writing to stdout: %s\n",argv[0],strerror(errno));
retval=1;
break;
}
}
if(ferror(input))
fprintf(stderr,"%s: error reading %s: %s\n",argv[0],argv[i-1],strerror(errno));
if(input!=stdin)
retval|=fclose(input);
}
return retval;
}
perl -ne print
perl -ne print text-file.txt
echo "fuck you" | perl -ne print
main = interact id
while(1) { putc(getc)); }