# Simple cat program

One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

• If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).
• If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

• This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

• Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

• Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

Also note that languages do have to fulfil our usual criteria for programming languages.

• If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

• Unless they have been overruled earlier, all standard rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

### Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

• Bash, 3 bytes: cat – TheDoctor Oct 31 '15 at 19:02
• @TheDoctor I guess this would fall into the "don't use a builtin which does exactly what is needed" rule. – Paŭlo Ebermann Oct 31 '15 at 19:46
• @PaŭloEbermann There is no such rule, and the corresponding standard loophole is no longer accepted. (In fact, there is already a sh answer using cat which also contains a shorter solution using dd.) – Martin Ender Oct 31 '15 at 20:25
• If only it used standard methods of input and output: ///, 0 bytes. – Comrade SparklePony Mar 31 '17 at 19:33
• @SparklePony Except, you'd have to escape slashes and backslashes. – Martin Ender Mar 31 '17 at 20:35

# Visual Basic.NET, 87 bytes

Imports c=System.Console
Module A
Sub Main
Main
End Sub
End Module

Similar to my C# answer. Here, a recursive call to Main (!) turned out to be the fastest way to loop. Microsoft's vbc doesn't complain, but I don't know if it's secretly filling the stack.

# HTML + JavaScript, 174 Bytes

min:

<input id="i"/><p id="o"></p><script>p=function(){o.textContent=i.value};o=document.getElementById('o');i=document.getElementById('i');i.addEventListener('keyup',p);</script>

var pipe = function () { output.textContent = input.value; },
output = document.getElementById('output'),
input = document.getElementById('input');
<input id="input"/>
<p id="output"></p>

# Ceylon (on JVM), 141111 108

This was my first try:

shared void run() {
print(l);
}
}

After removing spaces, we get this 64-character program: shared void run(){while(exists l=process.readLine()){print(l);}}

But this will not work with the yes | tr -d \\n | pipe, failing in an OutOfMemory error on the JVM (and failing with process.readLine not supported on this platform. in JavaScript).

It turns out that there is no cross-platform way of accessing the standard input in a not line-based way.

On the JVM, we can use Java libraries (including the standard packages). So this program works (it needs an import java.base "7"; and an native("jvm") annotation in the module descriptor):

import java.lang {
System {
i=\iin,
o=\iout
},
B=ByteArray
}

shared void run() {
B a = B(1000);
variable Integer s;
while (0 < (s = i.read(a))) {
o.write(a, 0, s);
}
}

It simply takes the Streams in and out in java.lang.System, and uses the standard way of copying from one to the other. java.lang.ByteArray is nothing else than the Ceylon name for the Java type byte[]. I use alias imports to save some characters (a default trick when we have to import something anyways).

Without line breaks this is this 141-byte code:

import java.lang{System{i=\iin,o=\iout},B=ByteArray}shared void run(){B a=B(1000);variable Integer s;while(0<(s=i.read(a))){o.write(a,0,s);}}

In Java that would have been written this way (wrapped in a class, and with an import of IOException):

public static void cat() throws IOException {
final byte[] a = new byte[1000];
int s;
while (0 < (s = System.in.read(a))) {
System.out.write(a, 0, s);
}
}

Of course, instead of allocating an array of size 1000 (which takes 4 bytes of source size), we can use 9, saving 3 bytes for some performance loss. Which brings us to the idea to get rid of the s variable – if the array has size 1, the result of read will be either 1 or -1 (and in the latter case we stop the loop). This gives us this loop (with the same imports as before):

shared void run() {
B a = B(1);
o.write(a);
}
}

It turns out that having just an integer variable instead of the byte-array is actually one byte longer (while we save the import, we need to declare the variable shared):

import java.lang {
System {
i=\iin,
o=\iout
}
}

shared void run() {
variable Integer r;
o.write(r);
}
}

So we use the 111-byte variant:

We can shorten it a tiny bit more by removing the imports for System.in and System.out, and using them directly in the code. Here is a commented version of the result:

// An implementation of a part of the functions of the standard unix utility cat.
// This program simply copies bytes from standard input to standard output, ignoring
// any command line arguments.
// Question: http://codegolf.stackexchange.com/q/62230/2338

// It turns out that there is no pure-Ceylon way of accessing standard input
// in a non-line-based way (which would break when given long input without
// line breaks).
// But when compiling for and running on the JVM, we can use Java's library.

// we need to import stuff from java.lang.
import java.lang {
// this has the standard streams in and out.
S=System,
// this corresponds to byte[].
B=ByteArray
}

shared void run() {
// create an array of size 1.
B a = B(1);

// As in is a keyword in Ceylon, we need to prefix it
// with \i to be able to use it as an identifier. Same
// for out. If used those more than once, using an
// alias import would be better.

// read one byte from System.in into the array.
// if nothing was read (→ -1), we stop.
// write the written byte to stdout.
S.\iout.write(a);
}
}

After comment and space removal we get this 108 byte program:

# FRACTRAN, 0 bytes

To quote the Wikipedia article, a FRACTRAN program is run by updating an input integer n using the following rules:

1. For the first fraction f in the list for which nf is an integer, replace n by nf

2. Repeat this rule until no fraction in the list produces an integer when multiplied by n, then halt.

Rule 2 applies immediately because, well, there's no list.

(Note: I'm assuming here that input/output refers to the input and output integers, which is the closest alternative.)

• According to those rules, there's no reason it should be invalid. Somehow, from Conway's paper, though, I got the sense the list had to be non-empty. For instance, Wiki (paraphrasing Conway) says 'The simplest FRACTRAN program is a single instruction such as,' before presenting the classic addition program. Anyway, just wanted to back you up by saying that if anyone does take issue, you can just cite the equally trivial & undefeatable program 1/1! – AviFS Jul 10 at 12:11
• Just wanted to apologize for the incorrect program, guess the only non-empty program would be 1/n as n → ∞ … Also, btw, here's the TIO link – AviFS Jul 10 at 12:22

# Changeling, 0 bytes

Automatic reading and printing are the only forms of I/O in Changeling, meaning that all Changeling programs cannot handle infinite inputs and will append a newline to the output.

Try it online!

# Nhohnhehr, 41 bytes

+----+
| /0\|
|$?@\| | \1\| | #| +----+ Try it online! ## Thotpatrol, 119 bytes 📡JACKING IN📡 💦DM💦 THAUGHTY JO 🕵 📧🍆 JO 🕵 🍑📧 JO 🇺🇸REPORT UNPATRIOTIC ACTIVITY🇺🇸 Thotpatrol does not support support key-events outside of console input, so this is the most correct solution. Link to implementation: https://github.com/MindyGalveston/thotpatrol- # Bash, 2 bytes A less known(?) alternative to dd and cat itself: m4 Try it online! • This isn't a valid answer because m4 processes its input; it doesn't just copy stdin to stdout. Here's a TIO example. – Mitchell Spector Apr 12 at 20:14 # Whispers, 22 bytes > InputAll >> Output 1 Try it online! # Cubically, 13 12 bytes (~-1/1=&6@7) Cubically can finally do this! Yay! We've been working on adding input/conditionals/loops for a while and just got it finished. Explanation: ( open loop (can be looped unconditionally) ~ read character as input -1/1 set notepad to -1 (EOF) = compare with input buffer (implicit = defaults to =7) &6 if truthy, quit @7 print character ) loop infinitely Try it online! • :0 is unnecessary because it will exit the program if the notepad is ever set to anything but 0 – TehPers Aug 4 '17 at 18:51 • @TehPers Oh, didn't notice! Thanks – MD XF Aug 4 '17 at 18:52 # Funky, 28 bytes io.stdin().pipe(io.stdout()) Shouldn't be too surprising. Just pipes STDIN to STDOUT. Try it online! ## Rust, 59 bytes use std::io::*;fn main(){copy(&mut stdin(),&mut stdout());} A glob import can be used to shorten previous Rust solution. # Icon, 40 bytes procedure main() while write(read()) end Try it online! # FALSE, 10 bytes [^$1+][,]#

FALSE is a stack-based language that aims to have a very small compiler.

[condition][body]# is a while loop; this program is essentially just:

while((c = getchar()) + 1) { putchar(c); }

Specifically, ^ tries to read a byte and push it; on EOF, it pushes -1. $1+ duplicates the result and adds 1 to it: the result is 0 only on EOF. , prints the original character. 12Me21 saved a byte. • You can save 1 byte by replacing 1_> with 1+ (n+1 is only 0 when n is -1). – 12Me21 Jan 31 '18 at 13:58 # TI-Basic, 12 10 bytes While 1 Input Str1 Disp Str1 • Doesn't this need to loop and accept multiple lines/pieces of input? The rules aren't very clear in this case, but I think you do. – Shelvacu Oct 30 '15 at 20:25 • @Shel I will get right to it then! – DanTheMan Oct 30 '15 at 20:30 • You can't take input from Ans; Input is the closest thing to STDIN. Strings also need to be supported; you can fix that by taking input into Str1 instead of A. – lirtosiast Oct 31 '15 at 17:47 # Ly, 16 bytes Posting because I didn't know that &i existed when I did this. i[&oi[r91+r&oi]] Demo # Ahead, 6 bytes ~oi@j~ ~ causes the head to ignore all commands and keep moving until it encounters another ~. This means the head moves to the right edge of the board at the beginning. It then bounces off the edge and begins traveling left on its next movement step. When the head goes back to the left side and encounters the ~, it bounces off the left edge and travels right, skipping cells, and the cycle continues. Try it online! ~ keep moving, ignoring commands until next ~ o pop and print character i read character from stdin, bounce back if no input @ end program j skip next cell ~ # 2DFuck, 79 bytes !x>>>>>>>>vxvx[^^r![<r!]v![,x>r!]^![<r!]vr![>r!]vr![^^r![<r!]vv![^r.x>vr!]<]r!] Try it online! Explanation: !x>>>>>>>>vxvx Set [0|0], [8|1], [8|2] to true [ While the accumulator is true: ^^r![<r!]v Go back to [0|1] ![,x>r!] Read rightwards until first 1 ([8|1]) -> 8 bits ^![<r!]v Go back to [0|1] r![>r!] Find first one bit. This is [8|1] if we get a null byte (EOF) vr![ If the bit below is 0: ^^r![<r!]v Go back to [0|1] v![^r.x>vr!]< Print everything til the first 1 in row 2 ([8|2]), clearing all bits on row 1 before it. Stop at [7|2] ]r! Read and flip (so, exit if we have a 1 -> null byte) ] # Pepe, 8 bytes REEeReee Try it online! ## Explanation Simple. REEe - Get all input as string Reee - Print all input • You could change your code to REEeReee because numbers will print char code – u-ndefined Jul 11 '18 at 6:32 • @u_ndefined Oh, you're right. Fixed it, thanks. – RedClover Jul 11 '18 at 13:12 ## PUBERTY, 123 bytes It is May 1st, 2019, 4:21:09 AM.Y is in his bed, bored.His secret kink is J.Soon the following sounds become audible.oh yes The first 3 sentences are the required header as short as possible. Puberty only supports inputs of one character so this program only reads and outputs one character The oh command stores the character in the current register, and the yes command prints the ASCII char corresponding to the value of the current register. ## Scratch (scratchblocks2), 40 bytes when gf clicked ask[]and wait say(answer # Clojure, 19 bytes (print(slurp *in*)) Try it online! ## Beam - 10 bytes >r@v ^? < Explanation: | > When it loops around, > makes it go right | r Reads a character from STDIN | @ Prints the character | v Sends the pointer down | < Sends the pointer left | ? Bounces if EOF (which is supposed to cause a loop, but it stops the program I guess) | ^ Sends the pointer up, which makes a loop ## Brainflub, 3 bytes *| ### Explanation : takes user input * : outputs contents of stdin | : ends program Compiler # Turing Machine But Way Worse, 419 bytes 0 0 0 1 1 0 0 1 0 1 1 A 0 0 0 1 0 1 2 0 0 1 1 1 1 a 0 0 0 2 0 1 3 0 0 1 2 1 1 b 0 0 0 3 0 1 4 0 0 1 3 1 1 c 0 0 0 4 0 1 5 0 0 1 4 1 1 d 0 0 0 5 0 1 6 0 0 1 5 1 1 e 0 0 0 6 0 1 7 0 0 1 6 1 1 f 0 0 0 7 0 1 7 0 1 1 7 1 1 7 0 1 0 A 0 1 a 0 0 1 A 1 1 a 0 0 0 a 0 1 b 0 0 1 a 1 1 b 0 0 0 b 0 1 c 0 0 1 b 1 1 c 0 0 0 c 0 1 d 0 0 1 c 1 1 d 0 0 0 d 0 1 e 0 0 1 d 1 1 e 0 0 0 e 0 1 f 0 0 1 e 1 1 f 0 0 0 f 0 1 0 1 0 1 f 1 1 0 1 0 Try it online! Full cat program. • Your efforts to make this answer have been modified to solve this challenge. Thought I'd let you know – MilkyWay90 Jul 31 '19 at 16:45 # 05AB1E, 2 bytes I? Try it online! Blank program is not allowed since OP specified "You should write a full program which reads..." • Doesn't seem to work for multiple lines. Though for one line, the empty program does work – Jo King Aug 24 '19 at 14:13 • @JoKing Thanks, I'll improve my this version. – mekb Aug 24 '19 at 22:16 • Also, I don't see why zero-length programs aren't valid "full programs" (that rule means functions aren't allowed) – pppery Aug 25 '19 at 1:44 • @pppery Oh, really. I thought they mean no 0 byte programs, since I don't see any 0b programs. – mekb Aug 25 '19 at 2:50 • The very old TeaScript answer is 0 bytes, and that's just the first one that I've noticed, so as long as it works a 0-byter is fine. In this case, it doesn't work, and neither does I? – Unrelated String Aug 26 '19 at 20:53 # Starry, 10 8 bytes  , + .' Try it Online! # Jasmin, 355331 299 bytes The resulting class file needs to be invoked with java -noverify. This code works for infinite inputs and can handle null bytes. .class C .super java/io/PrintStream .method public static main([Ljava/lang/String;)V T: getstatic java/lang/System/out Ljava/io/PrintStream; getstatic java/lang/System/in Ljava/io/InputStream; invokevirtual java/io/InputStream/read()I dup ifge$+4
return
invokevirtual C/print(C)V
goto T
.end method

# Golfing it almost 4 years later

1. Removed i2c before invoking print (-4 bytes)
2. Removed .limit stack 2 (-15 bytes)
3. Extend PrintStream instead of Object to shorten invocation of print (-15 bytes)
4. Return in the middle of the method instead of end. This makes on the the branch offsets shorter making the next change possible
5. Make one of the branches a relative offset. This only saves a byte when the relatice offset is less than or equal to 9 (-1 byte)
6. Store input byte on the stack instead of going through a local variable
• You could remove the return stuff because of -noverify iirc – famous1622 Dec 10 '19 at 20:52
• @famous1622 I think I tried that while golfing. The program compiles and runs correctly until it reaches the end of the input and the JVM segfaults. Unfortunately an error message is sent to stdout and not stderr, so that invalidates it for this challenge. – ankh-morpork Dec 10 '19 at 21:17

## Reflections, 61 53 bytes

\ v0):v+\
*/;++ ^;/
0 >~\
|:^+|
#@_
\ ^  0\
\   */

Test it in the browser!

Can handle infinite input (check the "Interactive" box), but not null bytes.

As Reflections takes linewise input, but doesn't preserve the newlines, getting those right was the first problem. Basically, a newline is printed before every line but the first.

Another problem was empty lines. An empty stack is falsy, just like a stack containing a 0 indicating end-of-file. Therefor stack size is explicitly checked.

Check the "Time between steps" box to see the messy control flow. Not that messy anymore.

# Stax, 1 bytes

m

Run and debug it

## Explaination

m as the first character uses the rest of the program to map input to output. A blank program just directly maps it. A blank stax program only outputs the first line of input.