84
\$\begingroup\$

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.

Task

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

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

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

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## 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>

\$\endgroup\$
  • 52
    \$\begingroup\$ Bash, 3 bytes: cat \$\endgroup\$ – TheDoctor Oct 31 '15 at 19:02
  • 3
    \$\begingroup\$ @TheDoctor I guess this would fall into the "don't use a builtin which does exactly what is needed" rule. \$\endgroup\$ – Paŭlo Ebermann Oct 31 '15 at 19:46
  • 5
    \$\begingroup\$ @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.) \$\endgroup\$ – Martin Ender Oct 31 '15 at 20:25
  • 1
    \$\begingroup\$ If only it used standard methods of input and output: ///, 0 bytes. \$\endgroup\$ – Comrade SparklePony Mar 31 '17 at 19:33
  • 1
    \$\begingroup\$ @SparklePony Except, you'd have to escape slashes and backslashes. \$\endgroup\$ – Martin Ender Mar 31 '17 at 20:35

264 Answers 264

0
\$\begingroup\$

rk, 52 bytes

read: key #   
while # > -1 do
print: #
read: #
done

Requires the -e flag (remove necessity for rk:start). Try it online!

Ungolfed:

rk:start
  key #
  read: #

  while # > -1 do
    print: #
    read: #
  done
rk:end
\$\endgroup\$
0
\$\begingroup\$

Canvas, 0 bytes


Try it here!

Canvas automatically adds the input to the stack before doing anything else, and also automatically prints the object at the top of the stack once all other instructions have been completed. Therefore, an empty program functions as an implicit cat.

\$\endgroup\$
  • \$\begingroup\$ Good, but not a very unique solution (any program which does that, like 05AB1E, would have a 0-byte solution). Try adding on another solution and try getting to 1 byte with that one. \$\endgroup\$ – MilkyWay90 Nov 10 '18 at 2:28
0
\$\begingroup\$

Implicit, 10 2 bytes

©"

© reads all input to the stack as ASCII characters, " turns the entire stack into a string.

Try it online!

A proper version

~.(-1@~.)&

Try it online! Explanation:

~+1(-1@;~+1)&
~            read character
 +1          increment
   (....     do
    -1        decrement
      @       print
       ~      read character
        +1    increment
          )  while top of stack truthy
           & exit (no implicit output)

All that incrementing and decrementing is to get the loop to exit on EOF (0).

\$\endgroup\$
0
\$\begingroup\$

Stax, 1 byte

_

Run and debug it

Null-bytes are always converted to spaces upon output. There are no ways to override this.

Multiple newlines are handled correctly. No extra trailing newlines if there are no trailing newlines in the input.

The language does not support infinite stream input.

\$\endgroup\$
0
\$\begingroup\$

Bitwise Cyclic Tag, 1 bit, 0.125 bytes

0

This will delete bits from the data tape (taking the starting data configuration as input) in order until there are none remaining to delete, at which point the program exits gracefully.

I'm on a phone now, but when I get the chance, I'll write an interpreter and post a TIO link.

\$\endgroup\$
0
\$\begingroup\$

Procedural Footnote Language, 33 bytes

[1]
[PFL1.0]
[1] [INPUT]
[PFLEND]

This program simply defines the body of the document as a reference to footnote [1], then defines the footnote as the value of the input from STDIN. The evaluated body of the document is printed as a result.

\$\endgroup\$
0
\$\begingroup\$

Reality, 0 bytes



This assumes that input is given (if it is not it will output something else)

\$\endgroup\$
0
\$\begingroup\$

Unnamed, 5 Chars

Unfortunately, this does not support newlines in the input, but whatever.

; # .

Explanation:

; > get input, put it into the current pointer
# > end command
. > print out the current pointer
\$\endgroup\$
  • \$\begingroup\$ Hi. Go to your gitHub and take a look. I suggested something \$\endgroup\$ – Muhammad Salman May 9 '18 at 8:07
0
\$\begingroup\$

Z80Golf, 7 bytes

00000000: cd03 8030 0176 d5                        ...0.v.

Try it online!

Disassembly

start:
  call $8003
  jr nc, skip
  halt
skip:
  push de
  • call $8003: Calls getchar. It sets carry flag on EOF, otherwise writes a byte to register a.
  • jr nc, skip: If carry flag is not set, jump to skip:. Otherwise the program hits halt and terminates.
  • push de: Pushes two zero bytes to the stack. The program runs through the NOPs in memory until it hits putchar at address $8000. Then the value in the register a is printed, and the program returns to the popped address, which is zero (start of the program).

This happens to be a slightly modified version of the one on the Esolangs page, where the position of push de is different. Using bc or hl instead of de equally works.

\$\endgroup\$
0
\$\begingroup\$

x86 assembly (16-bit, DOS)

Machine code:

b4 01 cd 21 eb fa

Source:

     mov $1, ah
.L1: int $0x21
     jmp .L1

Runs forever copying stdin to stdout, until you kill it.

\$\endgroup\$
  • \$\begingroup\$ Your program has to exit on EOF. \$\endgroup\$ – Dennis Aug 11 '18 at 1:37
  • \$\begingroup\$ I don't think that's meaningful here. \$\endgroup\$ – ObsequiousNewt Aug 11 '18 at 1:38
  • \$\begingroup\$ What do you mean? \$\endgroup\$ – Dennis Aug 11 '18 at 1:39
0
\$\begingroup\$

SNUSP (Modular), 11 bytes

/$\
. ,
\?/

Try it online!

Please note that the TIO doesn't work with input correctly, but the program is correct. In SNUSP, the instruction pointer starts at the $ moving right, and bounces off of slashes. When the IP goes over a ,, it reads a character from STDIN to the current memory cell. The ? tests whether or not the current value is 0. If it is, then then IP jumps over the next instruction (the \) and goes off the end of the program, terminating. Otherwise, the IP goes onto the \, reflects, and hits the ., printing the current value as a character to STDOUT. When the IP goes over the $ again, it doesn't do anything.

\$\endgroup\$
0
\$\begingroup\$

Flobnar, 6 bytes

~,_@
e

Try it online!

Suggested by Esolanging Fruit, this solution is much shorter, but ends in an error. Thanks!

Below is my old solution, which terminates correctly, but doesn't handle EOF correctly.

Flobnar, 15 bytes

|\<@:
:~
,0
_ ^

Try it online!

Explanation:

We start at the @, going left. The \ evaluates below it, and stores it in the call stack. This is either the next byte of input from ~, or 0 if it is EOF. Next, it passes through the | to check if the top value of the call stack (:) is non-zero. If it is not, the pointer goes down from the | and returns the top value of the call stack. Otherwise, it goes up and wraps around to the _. This is also a conditional, which first evaluates printing (,) the top of the call stack. Printing always returns 0, so it goes right to the ^ which starts the loop all over again.

\$\endgroup\$
  • \$\begingroup\$ 6-byte version that exits with an error \$\endgroup\$ – Esolanging Fruit Aug 12 '18 at 7:40
  • \$\begingroup\$ Also, I think this treats null bytes identically to EOF, which violates the rule that "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)". \$\endgroup\$ – Esolanging Fruit Aug 12 '18 at 7:43
0
\$\begingroup\$

bit, 16 bytes

IN
PRINT
PRINTLN

Explanation:

IN $$ Take input from user and push to stack
PRINT $$ add to printing queue
PRINTLN $$ Print the printing queue with a trailing newline

Bit is my own language, get the interpreter from GitHub and run:

java -jar bit.jar filename.bit
\$\endgroup\$
0
\$\begingroup\$

Backhand, 2 bytes

io

Try it online!

Seems obvious that i gets a character from the input and o outputs that character. However, the control flow is different from normal 2D languages in that it doesn't wrap around. Instead, the pointer moves three spaces, reflecting off the sides twice for each instruction.

\$\endgroup\$
0
\$\begingroup\$

Dots, 43453 bytes

....................................................................................................................................................................................................................................................................................................................................................................... and so on until 43453 bytes

I'll golf this later Nevermind, this is the least possible number of bytes, unless we assume that STDIN is one character long

\$\endgroup\$
  • \$\begingroup\$ Is this just another Unary clone? It's kinda hard to golf ,[.,] \$\endgroup\$ – Jo King Oct 30 '18 at 2:12
  • \$\begingroup\$ whats Unary? Also, once you learn the programming language, it becomes easy to golf \$\endgroup\$ – MilkyWay90 Oct 30 '18 at 2:12
  • \$\begingroup\$ It's just brainfuck converted to binary converted to unary. Unary \$\endgroup\$ – Jo King Oct 30 '18 at 2:20
  • \$\begingroup\$ Yikes, the programming language is remarkably similar. \$\endgroup\$ – MilkyWay90 Oct 30 '18 at 15:10
0
\$\begingroup\$

Common Lisp, 46 bytes

This is another, shorte, solution:

(loop while(setq x(read-char t()))do(princ x))

Try it online!

Note in that Common Lisp every output on standard output always produces a newline at end (due to its nature as interactive language). If the program above is run on a different output stream, the file does not contains the final newline if this is not present in the input stream.

\$\endgroup\$
0
\$\begingroup\$

Re:direction -A, 1 byte of codepage 437

Try it online!

The -A option allows Re:direction to interpret the input as the list of its character codes, rather than trying to parse numbers from it.

Explanation

In Re:direction, an arrow on a line by itself is a halt command. Arrows also change the command queue, but leftwards and upwards arrows don't have an effect on how the command queue is interpreted as I/O.

The input specifies the initial command queue, and the output is taken from the final command queue. So if we don't change it at all before halting (or change it only by adding leftwards or upwards arrows), the output will be the same as the input.

Re:direction also supports a more efficient character encoding than codepage 437, but the program wouldn't be any shorter.

\$\endgroup\$
0
\$\begingroup\$

!@#$%^&*()_+, 13 bytes

*!^(!_++@*!^)

Try it online!

Explanation

*!^(!_++@*!^)
*                add input to top of stack
 !               duplicate
  ^              increment
   (        )    while not zero (while not EOF):
    !_++         pop incremented entry (duplicate, negate, add twice)
        @        output original input
         *       add input to top of stack
          !      duplicate
           ^     increment
\$\endgroup\$
0
\$\begingroup\$

x86 assembly, 24 bytes (or 20 bytes)

Machine code:

42 b0 03 8d 0c 24 cd 80 3c 01 75 08 b0 04 43 cd 80 4b eb ed b0 01 cd 80

Source (AT&T syntax):

.section .text
.globl _start

_start:
    leal (%esp), %ecx  # read to (%esp)
    incl %edx          # read one byte

loop:
    movb $3, %al       # read (this is safe because %eax is initially 0)
    int $0x80          # %ebx starts at 0, so we're reading from stdin

    cmpb $1, %al       # exit if we didn't get exactly one byte
    jne quit

    movb $4, %al       # write (this is safe because return value of read is 1)
    incl %ebx          # stdout
    int $0x80
    decl %ebx          # back to stdin

    jmp loop

quit:
    movb $1, %al
    int $0x80

Try it online!

This program exits cleanly (with an exit code of 0, as a happy accident). A version that exits unpredictably (most likely with a segfault) can be produced by deleting the last four bytes, resulting in a 20 byte solution.

Tricks used:

  • Since %eax is only ever used to store bytes, and it is initially zero at the start of the program, we can treat %al as its own 8-bit register and never have to worry about the upper bits. This saves bytes with e.g. mov instructions, since movl with a constant takes up 5 bytes (1 for the instruction and 4 for the constant) whereas movb only takes 2 (1 for the instruction and 1 for the constant).

  • Similarly, instead of movl $1, %edx (5 bytes), incl %edx is only 1 byte and has the same effect, since %edx is initially zero.

  • We can take advantage of the fact that syscalls only clobber %eax by using the same values of the other registers for calls to sys_read as calls to sys_write. The only difference is the file descriptor, which we adjust from STDIN to STDOUT by a simple incl and change back afterwards with decl.

\$\endgroup\$
0
\$\begingroup\$

Tamsin, 12 bytes

main=any/''.

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Java, 133 bytes

No external libraries for me!

interface A{static void main(String[]a)throws Exception{for(;;)if(System.in.available()>0)System.out.print((char)System.in.read());}}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

@, 6 bytes

¤ōč

Explanation

¤   Forever,
 ō  output the
  č character input
\$\endgroup\$
0
\$\begingroup\$

05AB1E, 2 bytes

I?

Try it online!

Blank program is not allowed since OP specified "You should write a full program which reads..."

\$\endgroup\$
  • 2
    \$\begingroup\$ Doesn't seem to work for multiple lines. Though for one line, the empty program does work \$\endgroup\$ – Jo King Aug 24 at 14:13
  • \$\begingroup\$ @JoKing Thanks, I'll improve my this version. \$\endgroup\$ – facepalm42 Aug 24 at 22:16
  • 2
    \$\begingroup\$ Also, I don't see why zero-length programs aren't valid "full programs" (that rule means functions aren't allowed) \$\endgroup\$ – pppery Aug 25 at 1:44
  • \$\begingroup\$ @pppery Oh, really. I thought they mean no 0 byte programs, since I don't see any 0b programs. \$\endgroup\$ – facepalm42 Aug 25 at 2:50
  • \$\begingroup\$ 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? \$\endgroup\$ – Unrelated String Aug 26 at 20:53
0
\$\begingroup\$

Starry, 10 8 bytes

` , + .'

Try it Online!

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.