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
Dis, 2 bytes.
}{
Olmstead's cat program is too long, and it does not do really use the features of the language; just use that non-commands are NOP and the program counter loops over! Though the output would be slow, but this is pretty simple.
Java, 91 bytes
interface M{static void main(String[]a)throws Exception{System.in.transferTo(System.out);}}
Java, 101 bytes
interface M{static void main(String[]a)throws Exception{System.out.write(System.in.readAllBytes());}}
Java, 119 bytes
interface M{static void main(String[]a)throws Throwable{for(int i;(i=System.in.read())>-1;)System.out.print((char)i);}}
Java, 120 bytes
interface M{static void main(String[]a){System.out.print(new java.util.Scanner(System.in).useDelimiter("\\A").next());}}
CSASM v2.5.1, 36 bytes
func main:
ink ""
print
call main
ret
end
Waits for a key to be pressed, then prints that key (the input key is also printed by ink due to how it's coded) forever.
Explanation:
ink prompts the user with whatever string is used as its operand -- an empty string in this case -- then gets the input from the user and pushes it to the stack as a char value.
print prints the str representation of whatever value is on the stack and does not append a newline.
The code will then call main, causing infinite recursion. Eventually, it will stop due to a StackOverflowException but it will work just fine up until that point. The program can be halted by doing Ctrl + X.
CLC-INTERCAL, 82 bytes.
DO;2<-#1DOCOMEFROM#9DOWRITEIN;2(1)DO:1<-;2SUB#1DDOCOMEFROM':1~:1'~#1(9)DOREADOUT;2
Copy and paste to try it online!
How it works
DONOTE it shall have at most one byte
DO;2<-#1
DOCOMEFROM#9
DONOTE similar to getchar() but not really
DOWRITEIN;2
DONOTE checks if EOF
(1)DO:1<-;2SUB#1
DONOTE error exit
D
DONOTE come here unless EOF
DOCOMEFROM':1~:1'~#1
DONOTE no need to modify the array before outputting
(9)DOREADOUT;2
How I/O works in CLC-INTERCAL
- Has four methods but I know only three.
- Numeric I/O. Applied for spot and two-spot variables, almost as in INTERCAL-72 and C-INTERCAL.
- Input is done for each line. Each digit spelled. E.g.
ONE THREE TWO. - Output is done for each line, in Roman number. Instead of overlines, backslashes are used to indicate "times 1M".
- Input is done for each line. Each digit spelled. E.g.
- Baudot I/O. Applied for tail. Input is done like
gets(); outputs likeputs()so it's done every line.- It uses extended Baudot character set; a character
`is missing.
- It uses extended Baudot character set; a character
- Binary I/O. Applied for hybrid array.
- How WRITE IN works: if an array to be WRITTEN has N items, then N bytes are WRITTEN.
- Let io=172 and i=1.
- If i>N; then end.
- Let c=getchar().
- If c is EOF, then i-th item will be #0.
- If c is not EOF, then i-th item will be interleave(select(c,io),select(~c,~io)). In this expression c and io have 8 bits.
- If c is not EOF, then io=c.
- If c is not EOF, then most significant 16 bits of i-th item will be randomized so that at least one bit of them will be 1.
- Increment i. Go to step 2.
- READING OUT is done in reverse way.
- Variable "io" is initialized to 172 every time you WRITEIN and READOUT.
- How WRITE IN works: if an array to be WRITTEN has N items, then N bytes are WRITTEN.
Python, 14 bytes
print(input())
Print input... couldn't be more self-explanatory.
makina, (削除) 6 (削除ここまで) 3 bytes
I misread the requirements as needing a loop, whoops
Because makina is written in Python and uses Python's I/O methods, the information from the Python answer also applies to this answer.
P
i
C#, 76 bytes
for(int c=Console.Read();c!=-1;c=Console.Read())Console.Write((char)c);
x86 assembly (32-bit Linux), 19 bytes
Turned out almost identical to Doorknob's answer, so I'm not sure where the one byte saved came from. Uses same tricks: registers start zeroed and syscalls don't clobber any registers besides eax. (Probably) segfaults on EOF.
global _start
section .text
_start:
inc edx ; set edx = 1
mov ecx, esp ; read/write to sp
loop:
mov al, 3 ; read call number 3
; ebx: read from stdin (fd=0)
; edx: read 1 char
int 0x80 ; syscall
test eax, eax ; check if byte read
jz exit
mov al, 4 ; write call number
inc ebx ; write to stdout (fd=1)
; ecx: use char in buf
; edx: write 1 char
int 0x80 ; syscall
dec ebx ; ebx = 0
jmp loop
exit:
; segfault instead of exiting
Objdump:
08049000 <_start>:
8049000: 42 inc edx
8049001: 89 e1 mov ecx,esp
08049003 <loop>:
8049003: b0 03 mov al,0x3
8049005: cd 80 int 0x80
8049007: 85 c0 test eax,eax
8049009: 74 08 je 8049013 <exit>
804900b: b0 04 mov al,0x4
804900d: 43 inc ebx
804900e: cd 80 int 0x80
8049010: 4b dec ebx
8049011: eb f0 jmp 8049003 <loop>
Trilangle, (削除) 14 (削除ここまで) 8 bytes
<>i,@##o
Try it on the online interpreter!
The interpreter loads this into a triangular grid and adds trailing .s as necessary. When expanded, this program becomes:
<
> i
, @ #
# o . .
The IP starts on the north corner headed southwest.
Starting on the red path, the interpreter hits the following instructions:
<: Redirect the IP left, where it wraps around to the right side of the next rowi: Read a single character from input>: Branch
When it hits the branch instruction, the IP changes direction depending on the sign of the character read. EOF is -1 and all other characters are positive, so it branches on EOF.
When it reads EOF, it continues on the green path, and quickly hits @, terminating the program. Otherwise, it continues on the blue path:
o: Output a character,: Pop from the stack#: Skip the next instruction (twice)
After this, it reaches the <, where it merges with the red path.
The , instruction is necessary to keep memory bounded when fed an infinite input stream (e.g. when piping yes into it).
Uiua, 18 bytes SBCS
These take advantage of &sc returning 0 upon reaching EOF.
⍢&pf(≠0⊡0⇌utf.&sc)
This version errors since upon reaching EOF, Uiua then tries to index a non-existent first element of the utf array, which in that case is empty (has length 0).
⍢&pf(≠0⊡0⇌utf.&sc)
&sc # Read a line from stdin
. # Duplicate
utf # Convert to array of UTF-8 bytes
⇌ # Reverse array
⊡0 # Index the first element of said array
≠0 # Is not equal to 0?
( ) # Enclose as function
⍢&pf # Print to stdout while function condition is true (without trailing newline)
Non-erroring, 20 bytes SBCS
⍢&pf(≠0⊡0⇌⊂0utf.&sc)
This version does not error since it takes 2 more bytes to join a 0 to the utf array before indexing.
⍢&pf(≠0⊡0⇌⊂0utf.&sc)
&sc # Read a line from stdin
. # Duplicate
utf # Convert to array of UTF-8 bytes
⊂0 # Join a 0 to said array
⇌ # Reverse array
⊡0 # Index the first element of array
≠0 # Is not equal to 0?
( ) # Enclose as function
⍢&pf # Print to stdout while function condition is true (without trailing newline)
x86 assembly (16-bit, DOS), 6 bytes
Machine code:
b4 01 cd 21 eb fa
Source:
mov 1,ドル ah
.L1: int 0ドルx21
jmp .L1
Runs forever copying stdin to stdout, until you kill it.
-
\$\begingroup\$ Your program has to exit on EOF. \$\endgroup\$Dennis– Dennis2018年08月11日 01:37:46 +00:00Commented Aug 11, 2018 at 1:37
-
\$\begingroup\$ I don't think that's meaningful here. \$\endgroup\$ObsequiousNewt– ObsequiousNewt2018年08月11日 01:38:15 +00:00Commented Aug 11, 2018 at 1:38
-
\$\begingroup\$ What do you mean? \$\endgroup\$Dennis– Dennis2018年08月11日 01:39:22 +00:00Commented Aug 11, 2018 at 1:39
-
\$\begingroup\$ 21h interrupt checks ^C if that counts. \$\endgroup\$qwr– qwr2023年02月11日 00:11:39 +00:00Commented Feb 11, 2023 at 0:11
Bitwise, 27 bytes
IN 1 &1 2
OUT 1 2
JMP &-3 2
Commented:
IN 1 &1 2 read a character from standard input into register 1 if literal 1 is nonzero, store result in 2
OUT 1 2 output the character in register 1 if register 2 is nonzero, discard result
JMP &-3 2 jump 3 (2) lines backwards if register 2 is nonzero
The proper program would look like this:
LABEL &1 create label 1
IN 1 &1 2 (same as previous)
OUT 1 2 (same as previous)
JMP @1 2 jump back to label 1 if register 2 is nonzero
Momema, 18 bytes
z1-9*0z00*-9z=+1*0
Explanation
# var a
z 1 # label z0: jump past label z1 # loop body (initially skip this):
-9 *0 # print chr [0] # print chr a
z 0 # label z1: jump past label z1 (no-op) # end loop body
0 *-9 # [0] = read chr # a = read chr
z =+1*0 # label z2: jump past label z((!!([0] + 1) + 2) % 3) # if a != -1, go to loop body
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
Canvas, 0 bytes
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.
-
\$\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– MilkyWay902018年11月10日 02:28:50 +00:00Commented Nov 10, 2018 at 2:28
Implicit, (削除) 10 (削除ここまで) 2 bytes
©"
© reads all input to the stack as ASCII characters, " turns the entire stack into a string.
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).
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.
Reality, 0 bytes
This assumes that input is given (if it is not it will output something else)
Z80Golf, 7 bytes
00000000: cd03 8030 0176 d5 ...0.v.
Disassembly
start:
call 8003ドル
jr nc, skip
halt
skip:
push de
call 8003ドル: Callsgetchar. It sets carry flag on EOF, otherwise writes a byte to registera.jr nc, skip: If carry flag is not set, jump toskip:. Otherwise the program hitshaltand terminates.push de: Pushes two zero bytes to the stack. The program runs through the NOPs in memory until it hitsputcharat address8000ドル. Then the value in the registerais 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.
SNUSP (Modular), 11 bytes
/$\
. ,
\?/
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.
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
Backhand, 2 bytes
io
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.
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
-
\$\begingroup\$ Is this just another Unary clone? It's kinda hard to golf
,[.,]\$\endgroup\$Jo King– Jo King2018年10月30日 02:12:01 +00:00Commented Oct 30, 2018 at 2:12 -
\$\begingroup\$ whats Unary? Also, once you learn the programming language, it becomes easy to golf \$\endgroup\$MilkyWay90– MilkyWay902018年10月30日 02:12:45 +00:00Commented Oct 30, 2018 at 2:12
-
-
\$\begingroup\$ Yikes, the programming language is remarkably similar. \$\endgroup\$MilkyWay90– MilkyWay902018年10月30日 15:10:58 +00:00Commented Oct 30, 2018 at 15:10
cat\$\endgroup\$shanswer usingcatwhich also contains a shorter solution usingdd.) \$\endgroup\$