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_catshould print an infinite stream ofys. 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 fulfill 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 code-golf rules apply, including the loopholes that are forbidden by default.
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>
341 Answers 341
-
1\$\begingroup\$ This isn't a valid answer because
m4processes its input; it doesn't just copy stdin to stdout. Here's a TIO example. \$\endgroup\$Mitchell Spector– Mitchell Spector2020年04月12日 20:14:49 +00:00Commented Apr 12, 2020 at 20:14
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
-
\$\begingroup\$
:0is unnecessary because it will exit the program if the notepad is ever set to anything but 0 \$\endgroup\$TehPers– TehPers2017年08月04日 18:51:52 +00:00Commented Aug 4, 2017 at 18:51 -
\$\begingroup\$ @TehPers Oh, didn't notice! Thanks \$\endgroup\$MD XF– MD XF2017年08月04日 18:52:43 +00:00Commented Aug 4, 2017 at 18:52
Funky, 28 bytes
io.stdin().pipe(io.stdout())
Shouldn't be too surprising. Just pipes STDIN to STDOUT.
Rust, 59 bytes
use std::io::*;fn main(){copy(&mut stdin(),&mut stdout());}
A glob import can be used to shorten previous Rust solution.
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.
-
\$\begingroup\$ You can save 1 byte by replacing
1_>with1+(n+1 is only 0 when n is -1). \$\endgroup\$12Me21– 12Me212018年01月31日 13:58:09 +00:00Commented Jan 31, 2018 at 13:58
TI-Basic, (削除) 12 (削除ここまで) 10 bytes
While 1
Input Str1
Disp Str1
-
\$\begingroup\$ 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. \$\endgroup\$Shelvacu– Shelvacu2015年10月30日 20:25:01 +00:00Commented Oct 30, 2015 at 20:25
-
\$\begingroup\$ @Shel I will get right to it then! \$\endgroup\$DanTheMan– DanTheMan2015年10月30日 20:30:02 +00:00Commented Oct 30, 2015 at 20:30
-
1\$\begingroup\$ 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
Str1instead ofA. \$\endgroup\$lirtosiast– lirtosiast2015年10月31日 17:47:18 +00:00Commented Oct 31, 2015 at 17:47
Stax, 1 byte
_
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.
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.
~ 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!]
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)
]
-
\$\begingroup\$ You could change your code to
REEeReeebecause numbers will print char code \$\endgroup\$u-ndefined– u-ndefined2018年07月11日 06:32:32 +00:00Commented Jul 11, 2018 at 6:32 -
\$\begingroup\$ @u_ndefined Oh, you're right. Fixed it, thanks. \$\endgroup\$RedClover– RedClover2018年07月11日 13:12:37 +00:00Commented Jul 11, 2018 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.
Flobnar, 6 bytes
~,_@
e
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
_ ^
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.
-
\$\begingroup\$ 6-byte version that exits with an error \$\endgroup\$Esolanging Fruit– Esolanging Fruit2018年08月12日 07:40:11 +00:00Commented Aug 12, 2018 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– Esolanging Fruit2018年08月12日 07:43:06 +00:00Commented Aug 12, 2018 at 7:43
Scratch (scratchblocks2), 40 bytes
when gf clicked
ask[]and wait
say(answer
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
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 0ドルx80 # %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 0ドルx80
decl %ebx # back to stdin
jmp loop
quit:
movb 1,ドル %al
int 0ドルx80
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
%eaxis only ever used to store bytes, and it is initially zero at the start of the program, we can treat%alas its own 8-bit register and never have to worry about the upper bits. This saves bytes with e.g.movinstructions, sincemovlwith a constant takes up 5 bytes (1 for the instruction and 4 for the constant) whereasmovbonly takes 2 (1 for the instruction and 1 for the constant).Similarly, instead of
movl 1,ドル %edx(5 bytes),incl %edxis only 1 byte and has the same effect, since%edxis initially zero.We can take advantage of the fact that syscalls only clobber
%eaxby using the same values of the other registers for calls tosys_readas calls tosys_write. The only difference is the file descriptor, which we adjust from STDIN to STDOUT by a simpleincland change back afterwards withdecl.
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
Full cat program.
-
\$\begingroup\$ Your efforts to make this answer have been modified to solve this challenge. Thought I'd let you know \$\endgroup\$MilkyWay90– MilkyWay902019年07月31日 16:45:19 +00:00Commented Jul 31, 2019 at 16:45
05AB1E, 2 bytes
I?
Blank program is not allowed since OP specified "You should write a full program which reads..."
-
2\$\begingroup\$ Doesn't seem to work for multiple lines. Though for one line, the empty program does work \$\endgroup\$Jo King– Jo King2019年08月24日 14:13:36 +00:00Commented Aug 24, 2019 at 14:13
-
\$\begingroup\$ @JoKing Thanks, I'll improve my this version. \$\endgroup\$mekb– mekb2019年08月24日 22:16:34 +00:00Commented Aug 24, 2019 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\$The Fifth Marshal– The Fifth Marshal2019年08月25日 01:44:26 +00:00Commented Aug 25, 2019 at 1:44
-
\$\begingroup\$ @pppery Oh, really. I thought they mean no 0 byte programs, since I don't see any 0b programs. \$\endgroup\$mekb– mekb2019年08月25日 02:50:07 +00:00Commented Aug 25, 2019 at 2:50
-
1
Jasmin, (削除) 355 (削除ここまで) (削除) 331 (削除ここまで) 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
- Removed
i2cbefore invoking print (-4 bytes) - Removed
.limit stack 2(-15 bytes) - Extend
PrintStreaminstead ofObjectto shorten invocation of print (-15 bytes) - Return in the middle of the method instead of end. This makes on the the branch offsets shorter making the next change possible
- 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)
- Store input byte on the stack instead of going through a local variable
-
\$\begingroup\$ You could remove the return stuff because of -noverify iirc \$\endgroup\$Citty– Citty2019年12月10日 20:52:01 +00:00Commented Dec 10, 2019 at 20:52
-
\$\begingroup\$ @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. \$\endgroup\$ankh-morpork– ankh-morpork2019年12月10日 21:17:18 +00:00Commented Dec 10, 2019 at 21:17
Reflections, (削除) 61 (削除ここまで) 53 bytes
\ v0):v+\
*/;++ ^;/
0 >~\
|:^+|
#@_
\ ^ 0\
\ */
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
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.
Brainetry 0.1, 71 bytes
The golfed version is followed by the original reference program.
a b c d e f
a b c d e f g h
a b c d e f g
a b c d e f
a b c d e f g h i
To try this online head over to this link, paste the code in the btry/replit.btry file and hit the green "Run" button.
Ungolfed:
This program you are currently reading
has the particularity of explaining itself. In fact,
this program has one simple mission :
Take some input provided by you
and throw it right back at your face !!!
Windows Batch, 9 bytes
@type con
The type command is intended for reading files, but is perfectly capable of reading from STDIN.
Jellyfish, 7 bytes
PJ-1
5
The trailing newline is unavoidable since matrix print is the only printing function which keeps the input as is.
A jellyfish program is effectively a huge function which takes args via its branches that move down and to the right. So, effectively, this is what it parses to:
P (J (-1,5))
print_grid(input(-1,5))
-1 tells J to take input till EOF is reached.
-
\$\begingroup\$ This does work, you can remove the ? for implicit input, no? \$\endgroup\$Underslash– Underslash2021年06月16日 18:47:38 +00:00Commented Jun 16, 2021 at 18:47
-
\$\begingroup\$ @Underslash Oh, right... I forgot the default argument is the input \$\endgroup\$math scat– math scat2021年06月17日 13:57:26 +00:00Commented Jun 17, 2021 at 13:57
cat\$\endgroup\$shanswer usingcatwhich also contains a shorter solution usingdd.) \$\endgroup\$