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


<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 62230; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

• 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

Actually, 6 bytes

○W◙○WX


Try it online!

+2 bytes because I fixed the trailing newline issue.

tcl, 17

puts [read stdin]


To stop it from running, press Ctrl+D.

Perl 6, 25 bytes

.print while $_=$*IN.getc


Supports null-bytes, and infinite streams without newlines.

If we were allowed to work on a line-by-line basis and always print a trailing newline, it would be only 14 bytes:

.say for lines


Del|m|t, 14 bytes (non-competing)

Try it Online!

7 /  1 3 > ? 9


No command line argument, because is the default

Explanation:

(7) 23    Gets the next char from input (-1 if its EOF)
(/) 15    Duplicate
()  0     Pushes 0 (there are no characters -> ASCII sum = 0)
(1) 17    Swap top 2 (Stack is [C, 0, C])
(3) 19    Pushes 0 if (C >= 0), 1 Otherwise (i.e. EOF)

(>) 30, (?) 31    If the EOF has been reached, exit the program

(9) 25    Print the character
Repeat


SmileBASIC, 13 bytes

LINPUT S$?S$;


very simple.

Chip, 16 bytes

AabBCcdDEefFGghH


Try it online!

How it works:

Each capital letter corresponds to one bit of the input, and each lowercase letter to a bit of the output.

An input element, B will propagate its value to its immediate neighbors; in this case b and C. Being an output, b will take the value it has been given, and place that in the output. C will ignore B's signal, since input elements don't read the signals around them.

There won't be any cross-talk between output elements either, such as a and b, since neither produce any signal.

This isn't the only cat program, but all one-liners of this length will exhibit the wave-like pattern seen here. A 2D cat program (+3 bytes for newlines, but prettier imo) could be:

AabB
CcdD
EefF
GghH


Aceto, 5 bytes

When reading input, Aceto always waits for a newline, meaning input has to be \n-terminated.

pn
r<


In the current version, EOF will crash the program, but that only prints to STDERR.

OIL, 12 bytes

Can handle infinite input, but the input has to be newline-terminated (any other way isn't possible in OIL currently).

5
9
4
9
11
6


Alice, 4 bytes

i.To


Try it online!

Alice is a 2D language with two modes — Cardinal (i.e. up/down/left/right) which deals with integers and Ordinal (i.e. diagonal) which deals with strings. Here we only need Cardinal mode.

The naïve way would be

i.h%o


which would perform in a wraparound loop:

i        Read byte b, or produce -1 on EOF
.h%      Compute b%(b+1), erroring out for -1 or staying as b otherwise
'.' here is duplication, 'h' is increment and '%' is mod
o        Output (b mod 256) as a byte


However, instead of .h%, the answer uses a shorter way of erroring out:

i        Read byte b, or produce -1 on EOF
.T       Duplicate and sleep for b milliseconds, erroring out if b is negative
o        Output (b mod 256) as a byte


Of course, this means that the higher the byte values in the input, the longer the program will take to run!

Python 2, 28 bytes

while 1:
print(raw_input())


Try it online!

• Quite sure someone has tried that already. This is not gonna work for infinite input (without newline) :/ – daniero May 27 '17 at 16:13
• @daniero : Edited it. – LMD May 27 '17 at 17:27
• According to the rules, you should be able to run yes | tr -d \\n | python your_program.py and get some output. That doesn't seem to happen. – daniero May 27 '17 at 17:34

LOLCODE, 261 bytes

HAI 1.2
I HAS A s
I HAS A n ITZ 0
IM IN YR l
GIMMEH s
s,O RLY?
YA RLY
IM IN YR o UPPIN YR i TIL BOTH SAEM i AN n
VISIBLE ""
IM OUTTA YR o
VISIBLE s
n R 0
NO WAI
n R SUM OF 1 AN n
DIFFRINT n AN SMALLR OF n AN 9000,O RLY?
YA RLY
GTFO
OIC
OIC
IM OUTTA YR l
KTHXBYE


Try it online!

Cats aren't so simple after all. LOLCODE treats a blank line as falsey, and a "simple" cat program would stop and decide to take a nap as soon as it hits a blank line.

Given the 2008-era memes that spawned LOLCODE, I've decided that cats can't handle power levels over 9000, therefore this program will break if there are over 9000 empty lines. It also doesn't follow the rules about newlines (it will always print exactly one trailing newline, no matter how many trailing newlines the input had). I'm not sure any other way to do it in LOLCODE, since there's no way to differentiate between a blank line and the end of input.

Triangular, 6 bytes

\@~/;<


Triangular is my first attempt at a two-dimensional language. It is stack-based and the playing field is organized into the shape of a triangle. The above source code shapes into:

  \
@ ~
/ ; <


Each Triangular program starts at the top of the triangle with the IP moving Southwest.

• The \ command directs the IP to Southwest (the default direction but required for the loop).
• The ~ command reads a character from standard input and pushes it to the stack.
• The < command directs the IP to West.
• The ; command terminates the program if the top of stack is < 1.
• The / command directs the IP Northeast
• The @ command prints the top of stack as a character.
• The IP hits \ and loops.

Note that since the stack is never popped, this has a finite size. However, Triangular has 30kb stack, so I think this will suffice for most normal files, and you shouldn't be cat-ing executables anyway! ;-)

However, here's a version that can handle infinite input:

(.~..;)p@<


This shapes into a larger triangle:

   (
. ~
. . ;
) p @ <


There are only three different commands (and no IP redirects):

• ( open a loop
• p pop stack
• ) go to the most recent loop if the top of stack is > 0

I may be able to golf this if I change how Triangular reacts to playing field edges.

CPU-16 assembly, 56 bytes

load-a INPUT
write-flag EQ
cjmp EQ
write-extern A
jmp EQ


Needs a keyboard connected to the input port and a TTY to the output port.

Reads the input in a loop until it isn't zero, in which case it sends the input to the output and jumps back to the start of the program.

Foam, 5 bytes

,* ."


,* reads all the input, and then ." prints it as a string.

MOO, 81/75/41/35 bytes

while(!player:tell(read(player)))endwhile


or, 36 byte version if being run with wizard permissions:

while(!player:tell(read()))endwhile


Each of these versions will wait for a newline before printing, unless set_connection_option(player, "binary", 1) (40 bytes long) is called previously, as that is the nature of the input system.

Emmental, 24 bytes

;#44#46#35#52#50#63#42!*


Caker, 10 bytes

ωΩ(ξΘ)


(uses UTF-8)

Zucchini, 74 bytes

=0,1.12./.2.7./.3.6-/.4./.5./.1./.9,10.11+/.6.8./.9./.15./.13,/.13+/.12.0,


Ly, 4 bytes

&i&o


Try it online!

&i will copy all input onto the stack, &o outputs the stack.

Forked, 3 bytes

~,@


Yay, Forked is getting implemented!

• ~ - read character as input
• , - exit if <= 0
• @ - output as character
• wrap around (infinite loop)

Here's another, more interesting one: 9 bytes

>~,v
^-@<


Uses these directionals and no-ops (self-explanatory):

>  v
^- <


So the code is an infinite-loop like this:

~,@


Here's one that utilizes the fork: 13 bytes

>~v
@ |
^-:-&


Directionals and no-ops:

> v
|
^-:-


The fork will redirect the IP West if truthy and East if falsy. & is an exit.

;#*:), 5 bytes

*:#*)


Try it here!

Input must be terminated by a NUL byte. Can handle infinite input stream, and terminates at NUL bytes.

How it works

*     - Take a character of input
:  ) - While input is not a null byte...
#   -     Print as character
*  -     Take a character of input


var'aq, 25 bytes

~ Q { 'Ij cha' Q } pong Q


Explanation

A function named Q is pushed onto the stack which,'Ij - read from STDIN, cha' - write to STDOUT, and then calls itself recursively.

Unwanted, Unnecessary, Opportunistic, 0 bytes




If the script is empty - Unwanted, Unnecessary, Opportunistic just prints the input.

FEU, 0 bytes




Yep, the empty program works as a cat program...

Clora, 1 byte

!


Explanation:

! use Input as Output value

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.addEventListener('keyup', pipe);
<input id="input"/>
<p id="output"></p>

Ceylon (on JVM), 141111 108

import java.lang{S=System,B=ByteArray}shared void run(){B a=B(1);while(0<S.\iin.read(a)){S.\iout.write(a);}}


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:

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


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:

import java.lang{S=System,B=ByteArray}shared void run(){B a=B(1);while(0<S.\iin.read(a)){S.\iout.write(a);}}


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.)

Excel VBA, 6+1 = 7 Bytes

Since Excel VBA has no STDIN that handles input streams, the simplest way to address the prompt is to take input from a range on the ActiveSheet object (STDIN) and pass it onto the VBE immediate window (STDOUT)

?[A1];


Where [A1].Text has had ' preppended to its value (+1 Byte)

Alternative Version, 64 Bytes

To avoid the need for prepending the input with ', the user may instead check for an error or formula in [A1] and if so then return [A1].Formula else [A1] to the STDOUT in the VBE immediate window.

[B1]="=IsFormula(A1)":?IIf([IsErr(A1)]Or[B1],[A1].Formula,[A1]);
`
• Do you need to test if it is a formula first? It seems to work for plain text with '[A1].Formula' – seadoggie01 Sep 7 '18 at 16:02