Simple cat program

87

16

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>

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

Do we have to support multibyte characters? – Alex A. – 2015-10-30T19:46:40.060

@AlexA. Yes. Any byte-stream should work. – Martin Ender – 2015-10-30T19:47:00.950

53Bash, 3 bytes: cat – TheDoctor – 2015-10-31T19:02:30.533

3@TheDoctor I guess this would fall into the "don't use a builtin which does exactly what is needed" rule. – Paŭlo Ebermann – 2015-10-31T19:46:11.763

5@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 – 2015-10-31T20:25:31.807

Would it be acceptable to create this by taking the input from the user char by char instead of line by line? – J Atkin – 2015-11-01T13:28:20.177

@JAtkin Sure, many infinite-stream answers do that. You can read it in chunks as well, just don't wait for a specific character to appear. – Martin Ender – 2015-11-01T13:29:11.417

Do command line arguments count as STDIN? – user8397947 – 2016-06-06T23:08:27.493

@dorukayhan no, sorry. – Martin Ender – 2016-06-07T05:23:06.337

1If only it used standard methods of input and output: ///, 0 bytes. – Comrade SparklePony – 2017-03-31T19:33:12.623

1@SparklePony Except, you'd have to escape slashes and backslashes. – Martin Ender – 2017-03-31T20:35:26.160

@MartinEnder I always miss those sort of things. – Comrade SparklePony – 2017-03-31T20:38:10.463

If my language of choice cannot distinguish 0xFF bytes from EOF, can it halt on those instead of NUL bytes? – Dennis – 2017-09-16T14:02:33.620

@Dennis Seems fine. – Martin Ender – 2017-09-16T16:58:45.690

Answers

74

sed, 0


The empty sed program does exactly what is required here:

$ printf "abc\ndef" | sed ''
abc
def$ 

Digital Trauma

Posted 2015-10-30T16:16:15.190

Reputation: 64 644

3What happens if one writes yes | tr -d \\n | sed ''? – BenGoldberg – 2017-01-14T17:17:55.147

1@BenGoldberg By default sed works on a per-line basis, so in this case it will continue slurping up yeses into one pattern buffer until it runs out of memory. A caveat I suppose... – Digital Trauma – 2017-01-14T17:20:25.200

1POSIX mandates that the pattern space must have a size of at least 8192 bytes, IIRC. I know the GNU implementation has a dynamic pattern space, limited only by the available memory, so you're fairly safe on that one. – Toby Speight – 2018-05-09T14:03:00.900

60

Ziim, 222 201 196 185 182 bytes

    ↓ ↓

 ↓ ↓     ↓
 ↗ ↗↙↔↘↖ ↖
 ↓↓⤡⤢  ⤢↙
↘ ↖⤡ ↖
  ↙
  ↕↘ ↑ ↙
→↘↖↑ ↙ ↑
→↖   ↑
→↖↘ ↙
  ↑↓↑

   ⤡

This will probably not display correctly in your browser, so here is a diagram of the code:

enter image description here

I can't think of a simpler structure to solve the problem in Ziim, but I'm sure the actual code is still quite golfable.

Ziim cannot possibly handle infinite streams because it is only possible to print anything at the end of the program.

Explanation

Since Ziim has a rather unique, declarative control flow model an imperative pseudocode algorithm won't cut it here. Instead, I'll explain the basics of Ziim and the present the tidied up structure of the above code (in a similar graphical manner) as ASCII art.

Control flow in Ziim happens all over the place: each arrow which isn't pointed at by another arrow initialises a "thread" which is processed independently of the others (not really in parallel, but there are no guarantees which order they are processed in, unless you sync them up via concatenation). Each such thread holds a list of binary digits, starting as {0}. Now each arrow in the code is some sort of command which has one or two inputs and one or two outputs. The exact command depends on how many arrows are pointing at it from which orientations.

Here is the list of the commands, where m -> n indicates that the command takes m inputs and produces n outputs.

  • 1 -> 1, no-op: simply redirects the thread.
  • 1 -> 1, invert: negates each bit in the thread (and also redirects it).
  • 1 -> 1, read: replaces the thread's value by the next bit from STDIN, or by the empty list if we've hit EOF.
  • 2 -> 1, concatenate: this is the only way to sync threads. When a thread hits one side of the arrow, it will be suspended until another thread hits the other side. At that point they will be concatenated into a single thread and continue execution.
  • 2 -> 1, label: this is the only way to join different execution paths. This is simply a no-op which has two possible inputs. So threads entering the "label" via either route will simply be redirected into the same direction.
  • 1 -> 2, split: takes a single thread, and sends two copies off in different directions.
  • 1 -> 1, isZero?: consumes the first bit of the thread, and sends the thread in one of two directions depending on whether the bit was 0 or 1.
  • 1 -> 1, isEmpty?: consumes the entire list (i.e. replaces it with an empty list), and sends the thread in one of two direction depending on whether the list was already empty or not.

So with that in mind, we can figure out a general strategy. Using concatenate we want to repeatedly append new bits to a string which represents the entire input. We can simply do this by looping the output of the concatenate back into one of its inputs (and we initialise this to an empty list, by clearing a {0} with isEmpty?). The question is how we can terminate this process.

In addition to appending the current bit we will also prepend a 0 or 1 indicating whether we've reached EOF. If we send our string through isZero?, it will get rid of that bit again, but let us distinguish the end of the stream, in which case we simply let the thread leave the edge of the grid (which causes Ziim to print the thread's contents to STDOUT and terminate the program).

Whether we've reached EOF or not can be determined by using isEmpty? on a copy of the input.

Here is the diagram I promised:

              +----------------------------+   {0} --> isEmpty --> label <--+
              |                            |                    n    |      |
              v                            |                         v      |
    {0} --> label --> read --> split --> split ------------------> concat   |
                                 |                                   |      |
                           n     v     y                             |      |
 inv --> label --> concat <-- isEmpty --> concat <-- label <-- {0}   |      |
  ^        ^          |                     |          ^             |      |
  |        |          v                     v          |             |      |
 {0}       +------- split ---> label <--- split -------+             |      |
                                 |                                   |      |
                                 +-------------> concat <------------+      |
                                                   |                        |
                                              y    v                        |
                         print and terminate <-- isZero --------------------+

Some notes about where to start reading:

  • The {0} in the top left corner is the initial trigger which starts the input loop.
  • The {0} towards the top right corner is immediately cleared to an empty list an represents the initial string which we'll gradually fill with the input.
  • The other two {0}s are fed into a "producer" loop (one inverted, one not), to give us an unlimited supply of 0s and 1s which we need to prepend to the string.

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

29How can you even write a program like that without your brain exploding into a million little chunks of tissue. – Ashwin Gupta – 2015-12-28T16:15:31.603

41

Hexagony, 6 bytes

This used to be 3 bytes (see below), but that version no long works since the latest update of the language. As I never intentionally introduced the error that version made use of, I decided not to count it.


An error-free solution (i.e. one which works with the fixed interpreter) turns out to be much trickier. I've had some trouble squeezing it into a 2x2 grid, but I found one solution now, although I need the full 7 bytes:

<)@,;.(

After unfolding, we get:

enter image description here

Since the initial memory edge is 0, the < unconditionally deflects the instruction pointer into the North-East diagonal, where it wraps to the the grey path. The . is a no-op. Now , reads a byte, ) increments it such that valid bytes (including null bytes) are positive and EOF is 0.

So on EOF, the IP wraps to red path, where @ terminates the program. But if we still read a byte, then the IP wraps to the green path is instead where ( decrements the edge to the original value, before ; prints it to STDOUT. The IP now wraps unconditionally back to the grey path, repeating the process.


After writing a brute force script for my Truth Machine answer, I set it to find an error-free 6-byte solution for the cat program as well. Astonishingly, it did find one - yes, exactly one solution in all possible 6-byte Hexagony programs. After the 50 solutions from the truth machine, that was quite surprising. Here is the code:

~/;,@~

Unfolding:

enter image description here

The use of ~ (unary negation) instead of () is interesting, because a) it's a no-op on zero, b) it swaps the sides of the branch, c) in some codes a single ~ might be used twice to undo the operation with itself. So here is what's going on:

The first time (purple path) we pass through ~ it's a no-op. The / reflects the IP into the North-West diagonal. The grey path now reads a character and multiplies its character code by -1. This turns the EOF (-1) into a truthy (positive) value and all valid characters into falsy (non-positive) values. In the case of EOF, the IP takes the red path and the code terminates. In the case of a valid character, the IP takes the green path, where ~ undoes negation and ; prints the character. Repeat.


Finally, here is the 3-byte version which used to work in the original version Hexagony interpreter.

,;&

Like the Labyrinth answer, this terminates with an error if the input stream is finite.

After unfolding the code, it corresponds to the following hex grid:

enter image description here

The . are no-ops. Execution starts on the purple path.

, reads a byte, ; writes a byte. Then execution continues on the salmon(ish?) path. We need the & to reset the current memory edge to zero, such that the IP jumps back to the purple row when hitting the corner at the end of the second row. Once , hits EOF it will return -1, which causes an error when ; is trying to print it.


Diagrams generated with Timwi's amazing HexagonyColorer.

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

3The 6-byte version is very, very clever. Brute-forcers can be incredibly awesome. – ETHproductions – 2016-03-16T18:38:26.217

1Do you have a link to your brute-forcer? – MD XF – 2018-02-06T20:48:43.340

@MDXF I don't keep the various versions around, but it's always some modification of this Ruby script.

– Martin Ender – 2018-02-06T22:15:30.403

36

TeaScript, 0 bytes

TeaScript is a concise golfing language compiled to JavaScript


In a recent update the input is implicitly added as the first property.

Try it online


Alternatively, 1 byte

x

x contains the input in TeaScript. Output is implicit

Downgoat

Posted 2015-10-30T16:16:15.190

Reputation: 27 116

I was about to post this :) – user41805 – 2015-10-30T17:06:46.090

8Hah, I thought "Alternatively" was a language name... – Quelklef – 2018-09-08T22:32:09.620

29

Brian & Chuck, 44 bytes

#{<{,+?+}_+{-?>}<?
_}>?>+<<<{>?_}>>.<+<+{<{?

I originally created this language for Create a programming language that only appears to be unusable. It turns out to be a very nice exercise to golf simple problems in it though.

The Basics: Each of the two lines defines a Brainfuck-like program which operates on the other program's source code - the first program is called Brian and the second is called Chuck. Only Brian can read and only Chuck can write. Instead of Brainfuck's loops you have ? which passes control to the other program (and the roles of instruction pointer and tape head change as well). An addition to Brainfuck is { and } which scan the tape for the first non-zero cell (or the left end). Also, _ are replaced with null bytes.

While I don't think this is optimal yet, I'm quite happy with this solution. My first attempt was 84 bytes, and after several golfing sessions with Sp3000 (and taking some inspiration from his attempts), I managed to get it slowly down to 44, a few bytes at a time. Especially the brilliant +}+ trick was his idea (see below).

Explanation

Input is read into the first cell on Chuck's tape, then painstakingly copied to the end of Brian's tape, where it's printed. By copying it to the end, we can save bytes on setting the previous character to zero.

The # is just a placeholder, because switching control does not execute the cell we switched on. {<{ ensures that the tape head is on Chuck's first cell. , reads a byte from STDIN or -1 if we hit EOF. So we increment that with + to make it zero for EOF and non-zero otherwise.

Let's assume for now we're not at EOF yet. So the cell is positive and ? will switch control to Chuck. }> moves the tape head (on Brian) to the + the _ and ? passes control back to Brian.

{- now decrements the first cell on Chuck. If it's not zero yet, we pass control to Chuck again with ?. This time }> moves the tape head on Brian two cells of the right of the last non-zero cell. Initially that's here:

#{<{,+?+}_+{-?>}<?__
                   ^

But later on, we'll already have some characters there. For instance, if we've already read and printed abc, then it would look like this:

#{<{,+?+}_+{-?>}<?11a11b11c__
                            ^

Where the 1s are actually 1-bytes (we'll see what that's about later).

This cell will always be zero, so this time ? won't change control. > moves yet another cell to the right and + increments that cell. This is why the first character in the input ends up three cells to the right of the ? (and each subsequent one three cells further right).

<<< moves back to the last character in that list (or the ? if it's the first character), and {> goes back to the + on Brian's tape to repeat the loop, which slowly transfers the input cell onto the end of Brian's tape.

Once that input cell is empty the ? after {- will not switch control any more. Then >}< moves the tape head on Chuck to the _ and switches control such that Chuck's second half is executed instead.

}>> moves to the cell we've now written past the end of Brian's tape, which is the byte we've read from STDIN, so we print it back with .. In order for } to run past this new character on the tape we need to close the gap of two null bytes, so we increment them to 1 with <+<+ (so that's why there are the 1-bytes between the actual characters on the final tape). Finally {<{ moves back to the beginning of Brian's tape and ? starts everything from the beginning.

You might wonder what happens if the character we read was a null-byte. In that case the newly written cell would itself be zero, but since it's at the end of Brian's tape and we don't care where that end is, we can simply ignore that. That means if the input was ab\0de, then Brian's tape would actually end up looking like:

#{<{,+?+}_+{-?>}<?11a11b1111d11e

Finally, once we hit EOF that first ? on Brian's tape will be a no-op. At this point we terminate the program. The naive solution would be to move to the end of Chuck's tape and switch control, such that the program termiantes: >}>}<?. This is where Sp3000's really clever idea saves three bytes:

+ turns Chuck's first cell into 1. That means } has a starting point and finds the _ in the middle of Chuck's tape. Instead of skipping past it, we simply close the gap by turning it into a 1 with + as well. Now let's see what the rest of Brian's code happens to do with this modified Chuck...

{ goes back to Chuck's first cell as usual, and - turns it back into a null-byte. That means that ? is a no-op. But now >}<, which usually moved the tape head to the middle of Chuck's tape, moves right past it to the end of Chuck's tape and ? then passes control to Chuck, terminating the code. It's nice when things just work out... :)

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

26

Haskell, 16 bytes

main=interact id

interact reads the input, passes it to the function given as its argument and prints the result it receives. id is the identity function, i.e. it returns its input unchanged. Thanks to Haskell's laziness interact can work with infinite input.

nimi

Posted 2015-10-30T16:16:15.190

Reputation: 34 639

23

sh + binutils, 3 2 bytes

dd

Well, not quite as obvious. From @Random832

Original:

cat

The painfully obvious... :D

kirbyfan64sos

Posted 2015-10-30T16:16:15.190

Reputation: 8 730

12I'll do one better: dd. – Random832 – 2015-10-30T18:58:33.053

I was going to do cat... D: – ev3commander – 2015-11-06T00:08:19.937

2Yes, this is great and all... but 170 rep for typing cat??? – MD XF – 2017-06-10T23:59:04.097

1@MDXF what about who knows how much rep from a segfault? ;) – caird coinheringaahing – 2017-09-03T14:21:56.030

23

Funciton, 16 bytes

╔═╗
╚╤╝

(Encoded as UTF-16 with a BOM)

Explanation

The box returns the contents of STDIN. The loose end outputs it.

Timwi

Posted 2015-10-30T16:16:15.190

Reputation: 12 158

19

Motorola MC14500B Machine Code, 1.5 bytes

Written in hexadecimal:

18F

Written in binary:

0001 1000 1111

Explanation

1   Read from I/O pin
8   Output to I/O pin
F   Loop back to start

The opcodes are 4 bits each.

Zach Gates

Posted 2015-10-30T16:16:15.190

Reputation: 6 152

1-1 no screenshot, example or Try It Online link :P (jk) – MD XF – 2017-06-11T00:04:47.187

2+1. The only way I can think of to optimise this further would be to just solder the input pin to the output pin and take the chip out of it's socket :P – Wossname – 2017-06-19T08:35:18.443

16

Mornington Crescent, 41 bytes

Take Northern Line to Mornington Crescent

I have no idea whether Mornington Crescent can handle null bytes, and all input is read before the program starts, as that is the nature of the language.

pppery

Posted 2015-10-30T16:16:15.190

Reputation: 3 987

15

Brainfuck, 5 bytes

,[.,]

Equivalent to the pseudocode:

x = getchar()
while x != EOF:
    putchar(x)
    x = getchar()

This handles infinite streams, but treats null bytes as EOF. Whether or not BF can handle null bytes correctly varies from implementation to implementation, but this assumes the most common approach.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1DARN! You beat me to it by 5 mins! – kirbyfan64sos – 2015-10-30T16:29:37.310

If the first character is NULL then this won't run correctly. So it should be +[,.] right? – Shelvacu – 2015-10-30T17:41:03.557

6@Shel This is using 0x00 as the EOF byte. If the first character is EOF, it prints nothing, working as expected. – Mego – 2015-10-30T20:52:26.020

3"pseudocode" oh come on that's clearly just un-bracketed, un-semicolon-ed C :P – MD XF – 2017-06-11T00:03:09.037

14

Labyrinth, 2 bytes

,.

If the stream is finite, this will terminate with an error, but all the output produce by the error goes to STDERR, so the standard output stream is correct.

As in Brainfuck , reads a byte (pushing it onto Labyrinth's main stack) and . writes a byte (popping it from Labyrinth's main stack).

The reason this loops is that both , and . are "dead ends" in the (very trivial) maze represented by the source code, such that the instruction pointer simply turns around on the spot and moves back to the other command.

When we hit EOF , pushes -1 instead and . throws an error because -1 is not a valid character code. This might actually change in the future, but I haven't decided on this yet.


For reference, we can solve this without an error in 6 bytes as follows

,)@
.(

Here, the ) increments the byte we read, which gives 0 at EOF and something positive otherwise. If the value is 0, the IP moves straight on, hitting the @ which terminates the program. If the value was positive, the IP will instead take a right-turn towards the ( which decrements the top of the stack back to its original value. The IP is now in a corner and will simply keep making right turns, printing with ., reading a new byte with ., before it hits the fork at ) once again.

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

12

C, 40 bytes

main(i){while(i=~getchar())putchar(~i);}

Dennis

Posted 2015-10-30T16:16:15.190

Reputation: 196 637

main(){while(255-putchar(getchar()));} is a couple of bytes shorter. – Alchymist – 2015-11-03T13:50:39.010

1Sadly, that exits prematurely on 0xFF bytes and appends a 0xFF byte to the input if it doesn't contain it. – Dennis – 2015-11-03T13:58:37.193

What about the following, 36 bytes: main(){for(;;putchar(getchar()));}; – Johan du Toit – 2016-02-18T18:06:06.310

@user2943932 When it hits EOF, getchar returns -1, so your code will print an infinite stream of 0xFF bytes after the (finite) input. – Dennis – 2016-02-18T18:12:02.980

12

><>, 7 bytes

i:0(?;o

Try it here. Explanation:

i:0(?;o
i        Take a character from input, pushing -1 if the input is empty
 :0(     Check if the input is less than 0, pushing 1 if true, 0 if false
    ?;   Pop a value of the top of the stack, ending the program if the value is non-zero
      o  Otherwise, output then loop around to the left and repeat

If you want it to keep going until you give it more input, replace the ; with !.

DanTheMan

Posted 2015-10-30T16:16:15.190

Reputation: 3 140

Aww man, I was hoping to post the ><> answer... :P (+1!) – El'endia Starman – 2015-10-30T19:20:04.353

1io (2 bytes) does the same, but crashes and writes something smells fishy... to STDERR at the end of execution, which is allowed. – Lynn – 2015-10-31T12:25:42.307

@Mauris the online interpreter just outputs null bytes instead of ending with an error. – DanTheMan – 2015-11-02T12:28:27.237

11

X86 assembly, 70 bytes

Disassembly with objdump:

00000000 <.data>:
   0:   66 83 ec 01             sub    sp,0x1
   4:   66 b8 03 00             mov    ax,0x3
   8:   00 00                   add    BYTE PTR [eax],al
   a:   66 31 db                xor    bx,bx
   d:   66 67 8d 4c 24          lea    cx,[si+0x24]
  12:   ff 66 ba                jmp    DWORD PTR [esi-0x46]
  15:   01 00                   add    DWORD PTR [eax],eax
  17:   00 00                   add    BYTE PTR [eax],al
  19:   cd 80                   int    0x80
  1b:   66 48                   dec    ax
  1d:   78 1c                   js     0x3b
  1f:   66 b8 04 00             mov    ax,0x4
  23:   00 00                   add    BYTE PTR [eax],al
  25:   66 bb 01 00             mov    bx,0x1
  29:   00 00                   add    BYTE PTR [eax],al
  2b:   66 67 8d 4c 24          lea    cx,[si+0x24]
  30:   ff 66 ba                jmp    DWORD PTR [esi-0x46]
  33:   01 00                   add    DWORD PTR [eax],eax
  35:   00 00                   add    BYTE PTR [eax],al
  37:   cd 80                   int    0x80
  39:   eb c9                   jmp    0x4
  3b:   66 b8 01 00             mov    ax,0x1
  3f:   00 00                   add    BYTE PTR [eax],al
  41:   66 31 db                xor    bx,bx
  44:   cd 80                   int    0x80

The source:

sub esp, 1
t:
mov eax,3
xor ebx,ebx
lea ecx,[esp-1]
mov edx,1
int 0x80
dec eax
js e
mov eax,4
mov ebx,1
lea ecx,[esp-1]
mov edx,1
int 0x80
jmp t
e:
mov eax,1
xor ebx,ebx
int 0x80

kirbyfan64sos

Posted 2015-10-30T16:16:15.190

Reputation: 8 730

1So, objdump disassembled it as 32-bit code, while you seem to have compiled as 16-bit. What to believe? Since you use int 0x80, I guess it's meant for Linux, but why compile as 16-bit then? – Ruslan – 2015-11-02T13:08:28.910

@Ruslan I didn't even realize it was compiled in 16-bit... – kirbyfan64sos – 2015-11-02T14:35:25.500

11

Universal Lambda, 1 byte

!

A Universal Lambda program is an encoding of a lambda term in binary, chopped into chunks of 8 bits, padding incomplete chunks with any bits, converted to a byte stream.

The bits are translated into a lambda term as follows:

  • 00 introduces a lambda abstraction.
  • 01 represents an application of two subsequent terms.
  • 111..10, with n repetitions of the bit 1, refers to the variable of the nth parent lambda; i.e. it is a De Bruijn index in unary.

By this conversion, 0010 is the identity function λa.a, which means any single-byte program of the form 0010xxxx is a cat program.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1But ! is 0x21, not 0x4_? – wchargin – 2015-11-01T21:07:47.030

Fixed. -------- – Lynn – 2015-11-01T21:08:48.573

10

PowerShell, 88 41 30 Bytes

$input;write-host(read-host)-n

EDIT -- forgot that I can use the $input automatic variable for pipeline input ... EDIT2 -- don't need to test for existence of $input

Yeah, so ... STDIN in PowerShell is ... weird, shall we say. With the assumption that we need to accept input from all types of STDIN, this is one possible answer to this catalogue, and I'm sure there are others.1

Pipeline input in PowerShell doesn't work as you'd think, though. Since piping in PowerShell is a function of the language, and not a function of the environment/shell (and PowerShell isn't really solely a language anyway), there are some quirks to behavior.

For starters, and most relevant to this entry, the pipe isn't evaluated instantaneously (most of the time). Meaning, if we have command1 | command2 | command3 in our shell, command2 will not take input or start processing until command1 completes ... unless you encapsulate your command1 with a ForEach-Object ... which is different than ForEach. (even though ForEach is an alias for ForEach-Object, but that's a separate issue, since I'm talking ForEach as the statement, not alias)

This would mean that something like yes | .\simple-cat-program.ps1 (even though yes doesn't really exist, but whatever) wouldn't work because yes would never complete. If we could do ForEach-Object -InputObject(yes) | .\simple-cat-program.ps1 that should (in theory) work.

Getting to Know ForEach and ForEach-Object on the Microsoft "Hey, Scripting Guy!" blog.

So, all those paragraphs are explaining why if($input){$input} exists. We take an input parameter that's specially created automatically if pipeline input is present, test if it exists, and if so, output it.

Then, we take input from the user (read-host) via what's essentially a separate STDIN stream, and write-host it back out, with the -n flag (short for -NoNewLine). Note that this does not support arbitrary length input, as read-host will only complete when a linefeed is entered (technically when the user presses "Enter", but functionally equivalent).

Phew.

1But there are other options:

For example, if we were concerned with only pipeline input, and we didn't require a full program, you could do something like | $_ which would just output whatever was input. (In general, that's somewhat redundant, since PowerShell has an implicit output of things "left behind" after calculations, but that's an aside.)

If we're concerned with only interactive user input, we could use just write-host(read-host)-n.

Additionally, this function has the quirk feature of accepting command-line input, for example .\simple-cat-program.ps1 "test" would populate (and then output) the $a variable.

AdmBorkBork

Posted 2015-10-30T16:16:15.190

Reputation: 41 581

don't forget your built in aliases! – Chad Baxter – 2016-10-06T16:19:49.547

10

Cubix, 6 5 bytes

Now handles null bytes!

@_i?o

Cubix is a 2-dimensional, stack-based esolang. Cubix is different from other 2D langs in that the source code is wrapped around the outside of a cube.

Test it online! Note: there's a 50 ms delay between iterations.

Explanation

The first thing the interpreter does is figure out the smallest cube that the code will fit onto. In this case, the edge-length is 1. Then the code is padded with no-ops . until all six sides are filled. Whitespace is removed before processing, so this code is identical to the above:

  @
_ i ? o
  .

Now the code is run. The IP (instruction pointer) starts out on the far left face, pointing east.

The first char the IP encounters is _, which is a mirror that turns the IP around if it's facing north or south; it's currently facing east, so this does nothing. Next is i, which inputs a byte from STDIN. ? turns the IP left if the top item is negative, or right if it's positive. There are three possible paths here:

  • If the inputted byte is -1 (EOF), the IP turns left and hits @, which terminates the program.
  • If the inputted byte is 0 (null byte), the IP simply continues straight, outputting the byte with o.
  • Otherwise, the IP turns right, travels across the bottom face and hits the mirror _. This turns it around, sending it back to the ?, which turns it right again and outputs the byte.

I think this program is optimal. Before Cubix could handle null bytes (EOF was 0, not -1), this program worked for everything but null bytes:

.i!@o

I've written a brute-forcer to find all 5-byte cat programs. Though it takes ~5 minutes to finish, the latest version has found 5 programs:

@_i?o   (works as expected)
@i?o_   (works in exactly the same way as the above)
iW?@o   (works as expected)
?i^o@   (false positive; prints U+FFFF forever on empty input)
?iWo@   (works as expected)

ETHproductions

Posted 2015-10-30T16:16:15.190

Reputation: 47 880

Please don't edit a dozen posts at once. You're flooding the front page. 3 at a time is not an issue, but if you have to do more than that then please do your edits in small batches every 12 hours or so. – Martin Ender – 2016-09-07T09:48:09.090

@MartinEnder Sorry, I just noticed that. I'll space them out in the future. – ETHproductions – 2016-09-07T09:49:09.950

9

Vitsy, 2 bytes

zZ

z gets all of the input stack and pushes it to the active program stack. Z prints out all of the active stack to STDOUT.

Alternate method:

I\il\O
I\      Repeat the next character for input stack's length.
  i     Grab an item from the input.
   l\   Repeat the next character for the currently active program stack's length.
     O  Output the top item of the stack as a character.

Addison Crump

Posted 2015-10-30T16:16:15.190

Reputation: 10 763

2^_^ Have a +1 anyway! :) – El'endia Starman – 2015-10-30T16:35:59.870

Pity votes, my favorite! – Addison Crump – 2015-10-30T16:36:48.503

Why the downvotes? This seems to be a perfectly valid entry – Conor O'Brien – 2015-10-30T23:25:22.270

1It is valid by all specs. – Addison Crump – 2015-10-30T23:44:31.563

9

MarioLANG, 11 bytes

,<
."
>!
=#

I'm not entirely sure this is optimal, but it's the shortest I found.

This supports infinite streams and will terminate with an error upon reaching EOF (at least the Ruby reference implementation does).

There's another version of this which turns Mario into a ninja who can double jump:

,<
.^
>^
==

In either case, Mario starts falling down the left column, where , reads a byte and . writes a byte (which throws an error at EOF because , doesn't return a valid character). > ensures that Mario walks to the right (= is just a ground for him to walk on). Then he moves up, either via a double jump with ^ or via an elevator (the " and # pair) before the < tells him to move back to the left column.

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

8

rs, 0 bytes


Seriously. rs just prints whatever it gets if the given script is completely empty.

kirbyfan64sos

Posted 2015-10-30T16:16:15.190

Reputation: 8 730

7

GolfScript, 3 bytes

:n;

The empty program echoes standard input. The language cannot possibly handle infinite streams. However, it appends a newline, as @Dennis mentioned. It does so by wrapping the whole stack in an array and calling puts, which is defined as print n print, where n is a newline. However, we can redefine n to be STDIN, and then empty the stack, which is precisely what :n; does.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

7

Minkolang, 5 bytes

od?.O

Try it here.

Explanation

o reads in a character from input and pushes its ASCII code onto the stack (0 if the input is empty). d then duplicates the top of stack (the character that was just read in). ? is a conditional trampoline, which jumps the next instruction of the top of stack is not 0. If the input was empty, then the . is not jumped and the program halts. Otherwise, O outputs the top of stack as a character. The toroidal nature of Minkolang means that this loops around to the beginning.

El'endia Starman

Posted 2015-10-30T16:16:15.190

Reputation: 14 504

2Grar! You beat my language! UNACCEPTABLE! +1 – Addison Crump – 2015-10-30T16:35:02.160

7

Half-Broken Car in Heavy Traffic, 9 + 3 = 12 bytes

#<
o^<
 v

Half-Broken Car in Heavy Traffic (HBCHT) takes input as command line args, so run like

py -3 hbcht cat.hbc -s "candy corn"

Note that the +3 is for the -s flag, which outputs as chars. Also, HBCHT doesn't seem handle NULs, as all zeroes are dropped from the output (e.g. 97 0 98 is output as two chars ab).

Explanation

In HBCHT, your car starts at the o and your goal is the exit #. ^>v< direct the car's movement, while simultaneously modifying a BF-like tape (^>v< translate to +>-<). However, as the language name suggests, your car can only turn right – any attempts to turn left are ignored completely (including their memory effects). Note that this is only for turning – your car is perfectly capable of driving forward/reversing direction.

Other interesting parts about HBCHT are that your car's initial direction is randomised, and the grid is toroidal. Thus we just need the car to make it to the exit without modifying the tape for all four initial directions:

  • Up and down are straightforward, heading directly to the exit.

  • For left, we wrap and execute < and increment with ^. We can't turn left at the next < so we wrap and decrement with v, negating out previous increment. Since we're heading downwards now we can turn right at the < and exit, having moved the pointer twice and modifying no cell values.

  • For right, we do the same thing as left but skip the first ^ since we can't turn left.


Edit: It turns out that the HBCHT interpreter does let you execute just a single path via a command line flag, e.g.

py -3 hbcht -d left cat.hbc

However, not only is the flag too expensive for this particular question (at least 5 bytes for " -d u"), it seems that all paths still need to be able to make it to the exit for the code to execute.

Sp3000

Posted 2015-10-30T16:16:15.190

Reputation: 58 729

7

INTERCALL, 133 bytes

wat

INTERCALL IS A ANTIGOLFING LANGUAGE
SO THIS HEADER IS HERE TO PREVENT GOLFING IN INTERCALL
THE PROGRAM STARTS HERE:
READ
PRINT
GOTO I

TuxCrafting

Posted 2015-10-30T16:16:15.190

Reputation: 4 547

It looks like someone really golfed in a purely anti-golfing language... 133-116=17 – Erik the Outgolfer – 2016-06-16T10:13:09.407

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Since the cat program is pretty simple, this is'nt the case of all programs... http://codegolf.stackexchange.com/a/82748/53745

– TuxCrafting – 2016-06-16T13:36:11.217

The person who made the language intended to use roman numerals, but if it was the case to print 500 (not sure), it would be PRINT D, right? (excluding the header) – Erik the Outgolfer – 2016-06-16T13:52:07.000

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Nope, INTERCALL can only print ASCII characters and use a stack, so for example to print the caracter with ascii value 20 the code is PUSH XX<newline>PRINT or PUSH XX AND PRINT. Oh and i am the creator of INTERCALL – TuxCrafting – 2016-06-16T13:55:02.067

7

V, 0 bytes

Try it online!

V's idea of "memory" is just a gigantic 2D array of characters. Before any program is ran, all input it loaded into this array (known as "The Buffer"). Then, at the end of any program, all text in the buffer is printed.

In other words, the empty program is a cat program.

James

Posted 2015-10-30T16:16:15.190

Reputation: 54 537

6

Snowman 1.0.2, 15 chars

(:vGsP10wRsp;bD

Taken directly from Snowman's examples directory. Reads a line, prints a line, reads a line, prints a line...

Note that due to an implementation detail, when STDIN is empty, vg will return the same thing as it would for an empty line. Therefore, this will repeatedly print newlines in an infinite loop once STDIN is closed. This may be fixed in a future version.

Explanation of the code:

(        // set two variables (a and f) to active—this is all we need
:...;bD  // a "do-loop" which continues looping as long as its "return value"
         // is truthy
  vGsP   // read a line, print the line
  10wRsp // print a newline—"print" is called in nonconsuming mode; therefore,
         // that same newline will actually end up being the "return value" from
         // the do-loop, causing it to loop infinitely

Doorknob

Posted 2015-10-30T16:16:15.190

Reputation: 68 138

5

FireType, 7 bytes

,
&
_
=

Requires some changes I just pushed. The rules say:

Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge.

so I'm in the clear!

kirbyfan64sos

Posted 2015-10-30T16:16:15.190

Reputation: 8 730

5

Fission, 4 bytes

R?J!

Isn't it nice when you beat the sample programs in language's own repository? :) For reference, it has the 7-byte solution

R?J0;0!

Explanation

So, R starts the control-flow with a right-going atom. ? reads a character from STDIN into the atom's mass. As long as we're reading characters, the energy remains zero, so the Jump is a no-op and ! prints the character. The atom loops back to the start (R is now a no-op) and repeats the whole process.

When we hit EOF, ? will set the atom's energy to 1, so the Jump will now skip the print command. But when an atom hits ? after EOF has already been returned, it will destroy the atom instead, which terminates the program.

(The solution from the language's author uses an explicit ; to terminate the program, which is skipped with two 0-portals otherwise.)

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

5

Shtriped, 20 bytes

e )
"
 r )
 s )
 "
"

This cheekily demonstrates that nearly any printable ASCII string is a valid identifier in Shtriped.

How it works:

e )   \ declares a variable named )
"     \ defines a function with 0 arguments named "
 r )  \ gets a line of string input, saving it to )
 s )  \ prints ) as a string
 "    \ recursively calls ", effectively looping forever
"     \ calls " from the main scope to get things started

There's no real way to detect EOF, so this loops forever like the Python answer.

You can easily make it stop when an empty line is given though (30 bytes):

e )
"
 r )
 d ) \ tries to decrement ), if it was the empty string, aka 0, it can't, so 0 is returned all the way up
 i ) \ increment ) to put it back to normal after possibly decrementing
 s )
 "
"

Note that Shtriped I/O only supports printable ASCII, tabs, line feeds, carriage returns, vertical tabs, and form feeds (100 chars in total). This is because internally, strings are represented as non-negative arbitrary precision integers, and there must be a finite alphabet of characters to be able to encode all strings.

Calvin's Hobbies

Posted 2015-10-30T16:16:15.190

Reputation: 84 000

4

Python 2, 52 bytes

from sys import*
while 1:stdout.write(stdin.read(1))

Python will only echo when a newline has been pressed because by default the terminal only sends input to the program after a newline.

OR, 25 bytes

while 1:print raw_input()

In this program, the code explicitly waits for a newline before printing

Blue

Posted 2015-10-30T16:16:15.190

Reputation: 26 661

@Mego the issue is on read... but that only applies when input is a terminal, and depends on the terminal's mode. Though you can press Ctrl-D in the middle of a line to make it output immediately. – Random832 – 2015-10-30T19:01:39.883

@Mego Not in the middle of the line unless you press it twice without typing anything else. Try it and see. – Random832 – 2015-10-30T20:52:25.720

good catch, sorry – R Nar – 2015-10-30T20:59:22.960

No, this code is invalid in Python 2 as well. The semicolon should be a newline. – Lynn – 2015-10-30T23:46:44.857

@EriktheGolfer I'm doing stdin.read as well as stdout.write – Blue – 2016-09-27T18:07:13.883

@muddyfish Oh, sooo blind me!! – Erik the Outgolfer – 2016-09-27T18:08:09.047

4

gs2, 0 bytes


The empty program echoes standard input. The language cannot possibly handle infinite streams.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

4

CJam, 1 byte

q

CJam has three ways to read from the input stream:

  • q reads it all as one big string.
  • l reads a single line, up until a newline.
  • r reads a token, which is a sequence of non-whitespace characters.

As such, it has no way to handle an infinite stream of non-whitespace characters. This should make q a valid solution.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

4

Lazy K, 1 0 bytes

As CatsAreFluffy pointed out, the empty program has the same semantics as the program I. From the grammar:

  Program  ::= CCExpr                     CCExpr

  CCExpr   ::= CCExpr Expr                (CCExpr Expr)
             | epsilon                    (lambda (x) x)

Old explanation (1 byte)

I

A Lazy K program is a function on Church lists of Church numerals, expressed in SKI combinator logic. I is the identity function, which simply equates the output with the input. As such, a cat program is essentially the "simplest" Lazy K program. If your Lazy K interpreter is any good, it even handles infinite streams!

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

Doesn't the empty program work? – CalculatorFeline – 2016-03-18T02:39:48.530

Wow, you’re right. Thanks! – Lynn – 2016-03-18T09:25:36.203

So now we have sed, gs2, TeaScript, and LazyK with 0byte answers. Yay! – CalculatorFeline – 2016-03-18T15:37:14.637

4

Beam, 8 bytes

>rnH
\@/

Fairly simple and a little shorter than the one on the esolangs page.

MickyT

Posted 2015-10-30T16:16:15.190

Reputation: 11 735

4

Ouroboros, 9 4 bytes

i.)o

The program outputs the exact input, with no extraneous characters. It theoretically would work on null bytes and infinite streams, but as the only interpreter for the language is HTML/JavaScript and the input comes from a text box, neither concept is really applicable.

  • i reads a character code or -1 for end of input.
  • . duplicates it.
  • ) is an absolutely nasty hack.
    • Control flow in Ouroboros is accomplished via the ( and ) commands, which swallow and regurgitate characters from the end of a line. The program ends when the instruction pointer is swallowed. Normally, this means you'll need a ( instruction somewhere, or else the code is an infinite loop. However, in the current implementation, if you use a negative number as the argument to ) (regurgitate), it actually swallows characters. (I.e., regurgitates backwards??)
    • So: if i read a character and pushed its nonnegative character code, ) regurgitates a number of characters equal to that value--which does nothing, because the snake is already at its maximum possible size. But if i hit EOF and pushed -1, ) "regurgitates" -1 characters, meaning it actually swallows one.
    • On EOF, the o gets swallowed. The program does not output anything and loops again; i again gives -1, and another character is swallowed--this time, the ). Now the program halts, since the instruction pointer was swallowed.
  • If nothing was swallowed, o outputs the character from the stack. Control then loops back to the beginning of the line.

See it in action:

// Define Stack class
function Stack() {
  this.stack = [];
  this.length = 0;
}
Stack.prototype.push = function(item) {
  this.stack.push(item);
  this.length++;
}
Stack.prototype.pop = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack.pop();
    this.length--;
  }
  return result;
}
Stack.prototype.top = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack[this.length - 1];
  }
  return result;
}
Stack.prototype.toString = function() {
  return "" + this.stack;
}

// Define Snake class
function Snake(code) {
  this.code = code;
  this.length = this.code.length;
  this.ip = 0;
  this.ownStack = new Stack();
  this.currStack = this.ownStack;
  this.alive = true;
  this.wait = 0;
  this.partialString = this.partialNumber = null;
}
Snake.prototype.step = function() {
  if (!this.alive) {
    return null;
  }
  if (this.wait > 0) {
    this.wait--;
    return null;
  }
  var instruction = this.code.charAt(this.ip);
  var output = null;
  console.log("Executing instruction " + instruction);
  if (this.partialString !== null) {
    // We're in the middle of a double-quoted string
    if (instruction == '"') {
      // Close the string and push its character codes in reverse order
      for (var i = this.partialString.length - 1; i >= 0; i--) {
        this.currStack.push(this.partialString.charCodeAt(i));
      }
      this.partialString = null;
    } else {
      this.partialString += instruction;
    }
  } else if (instruction == '"') {
    this.partialString = "";
  } else if ("0" <= instruction && instruction <= "9") {
    if (this.partialNumber !== null) {
      this.partialNumber = this.partialNumber + instruction;  // NB: concatenation!
    } else {
      this.partialNumber = instruction;
    }
    next = this.code.charAt((this.ip + 1) % this.length);
    if (next < "0" || "9" < next) {
      // Next instruction is non-numeric, so end number and push it
      this.currStack.push(+this.partialNumber);
      this.partialNumber = null;
    }
  } else if ("a" <= instruction && instruction <= "f") {
    // a-f push numbers 10 through 15
    var value = instruction.charCodeAt(0) - 87;
    this.currStack.push(value);
  } else if (instruction == "$") {
    // Toggle the current stack
    if (this.currStack === this.ownStack) {
      this.currStack = this.program.sharedStack;
    } else {
      this.currStack = this.ownStack;
    }
  } else if (instruction == "s") {
    this.currStack = this.ownStack;
  } else if (instruction == "S") {
    this.currStack = this.program.sharedStack;
  } else if (instruction == "l") {
    this.currStack.push(this.ownStack.length);
  } else if (instruction == "L") {
    this.currStack.push(this.program.sharedStack.length);
  } else if (instruction == ".") {
    var item = this.currStack.pop();
    this.currStack.push(item);
    this.currStack.push(item);
  } else if (instruction == "m") {
    var item = this.ownStack.pop();
    this.program.sharedStack.push(item);
  } else if (instruction == "M") {
    var item = this.program.sharedStack.pop();
    this.ownStack.push(item);
  } else if (instruction == "y") {
    var item = this.ownStack.top();
    this.program.sharedStack.push(item);
  } else if (instruction == "Y") {
    var item = this.program.sharedStack.top();
    this.ownStack.push(item);
  } else if (instruction == "\\") {
    var top = this.currStack.pop();
    var next = this.currStack.pop()
    this.currStack.push(top);
    this.currStack.push(next);
  } else if (instruction == "@") {
    var c = this.currStack.pop();
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(c);
    this.currStack.push(a);
    this.currStack.push(b);
  } else if (instruction == ";") {
    this.currStack.pop();
  } else if (instruction == "+") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a + b);
  } else if (instruction == "-") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a - b);
  } else if (instruction == "*") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a * b);
  } else if (instruction == "/") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a / b);
  } else if (instruction == "%") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a % b);
  } else if (instruction == "_") {
    this.currStack.push(-this.currStack.pop());
  } else if (instruction == "I") {
    var value = this.currStack.pop();
    if (value < 0) {
      this.currStack.push(Math.ceil(value));
    } else {
      this.currStack.push(Math.floor(value));
    }
  } else if (instruction == ">") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a > b));
  } else if (instruction == "<") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a < b));
  } else if (instruction == "=") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a == b));
  } else if (instruction == "!") {
    this.currStack.push(+ !this.currStack.pop());
  } else if (instruction == "?") {
    this.currStack.push(Math.random());
  } else if (instruction == "n") {
    output = "" + this.currStack.pop();
  } else if (instruction == "o") {
    output = String.fromCharCode(this.currStack.pop());
  } else if (instruction == "r") {
    var input = this.program.io.getNumber();
    this.currStack.push(input);
  } else if (instruction == "i") {
    var input = this.program.io.getChar();
    this.currStack.push(input);
  } else if (instruction == "(") {
    this.length -= Math.floor(this.currStack.pop());
    this.length = Math.max(this.length, 0);
  } else if (instruction == ")") {
    this.length += Math.floor(this.currStack.pop());
    this.length = Math.min(this.length, this.code.length);
  } else if (instruction == "w") {
    this.wait = this.currStack.pop();
  }
  // Any unrecognized character is a no-op
  if (this.ip >= this.length) {
    // We've swallowed the IP, so this snake dies
    this.alive = false;
    this.program.snakesLiving--;
  } else {
    // Increment IP and loop if appropriate
    this.ip = (this.ip + 1) % this.length;
  }
  return output;
}
Snake.prototype.getHighlightedCode = function() {
  var result = "";
  for (var i = 0; i < this.code.length; i++) {
    if (i == this.length) {
      result += '<span class="swallowedCode">';
    }
    if (i == this.ip) {
      if (this.wait > 0) {
        result += '<span class="nextActiveToken">';
      } else {
        result += '<span class="activeToken">';
      }
      result += escapeEntities(this.code.charAt(i)) + '</span>';
    } else {
      result += escapeEntities(this.code.charAt(i));
    }
  }
  if (this.length < this.code.length) {
    result += '</span>';
  }
  return result;
}

// Define Program class
function Program(source, speed, io) {
  this.sharedStack = new Stack();
  this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
    var snake = new Snake(snakeCode);
    snake.program = this;
    snake.sharedStack = this.sharedStack;
    return snake;
  }.bind(this));
  this.snakesLiving = this.snakes.length;
  this.io = io;
  this.speed = speed || 10;
  this.halting = false;
}
Program.prototype.run = function() {
  this.step();
  if (this.snakesLiving) {
    this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
  }
}
Program.prototype.step = function() {
   for (var s = 0; s < this.snakes.length; s++) {
    var output = this.snakes[s].step();
    if (output) {
      this.io.print(output);
    }
  }
  this.io.displaySource(this.snakes.map(function (snake) {
      return snake.getHighlightedCode();
    }).join("<br>"));
 }
Program.prototype.halt = function() {
  window.clearTimeout(this.timeout);
}

var ioFunctions = {
  print: function (item) {
    var stdout = document.getElementById('stdout');
    stdout.value += "" + item;
  },
  getChar: function () {
    if (inputData) {
      var inputChar = inputData[0];
      inputData = inputData.slice(1);
      result = inputChar.charCodeAt(0);
    } else {
      result = -1;
    }
    var stdinDisplay = document.getElementById('stdin-display');
    stdinDisplay.innerHTML = escapeEntities(inputData);
    return result;
  },
  getNumber: function () {
    while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
      inputData = inputData.slice(1);
    }
    if (inputData) {
      var inputNumber = inputData.match(/\d+/)[0];
      inputData = inputData.slice(inputNumber.length);
      result = +inputNumber;
    } else {
      result = -1;
    }
    var stdinDisplay = document.getElementById('stdin-display');
    stdinDisplay.innerHTML = escapeEntities(inputData);
    return result;
  },
  displaySource: function (formattedCode) {
    var sourceDisplay = document.getElementById('source-display');
    sourceDisplay.innerHTML = formattedCode;
  }
};
var program = null;
var inputData = null;
function showEditor() {
  var source = document.getElementById('source'),
    sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
    stdin = document.getElementById('stdin'),
    stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');
  
  source.style.display = "block";
  stdin.style.display = "block";
  sourceDisplayWrapper.style.display = "none";
  stdinDisplayWrapper.style.display = "none";
  
  source.focus();
}
function hideEditor() {
  var source = document.getElementById('source'),
    sourceDisplay = document.getElementById('source-display'),
    sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
    stdin = document.getElementById('stdin'),
    stdinDisplay = document.getElementById('stdin-display'),
    stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');
  
  source.style.display = "none";
  stdin.style.display = "none";
  sourceDisplayWrapper.style.display = "block";
  stdinDisplayWrapper.style.display = "block";
  
  var sourceHeight = getComputedStyle(source).height,
    stdinHeight = getComputedStyle(stdin).height;
  sourceDisplayWrapper.style.minHeight = sourceHeight;
  sourceDisplayWrapper.style.maxHeight = sourceHeight;
  stdinDisplayWrapper.style.minHeight = stdinHeight;
  stdinDisplayWrapper.style.maxHeight = stdinHeight;
  sourceDisplay.textContent = source.value;
  stdinDisplay.textContent = stdin.value;
}
function escapeEntities(input) {
  return input.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function resetProgram() {
  var stdout = document.getElementById('stdout');
  stdout.value = null;
  if (program !== null) {
    program.halt();
  }
  program = null;
  inputData = null;
  showEditor();
}
function initProgram() {
  var source = document.getElementById('source'),
    stepsPerSecond = document.getElementById('steps-per-second'),
    stdin = document.getElementById('stdin');
  program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
  hideEditor();
  inputData = stdin.value;
}
function runBtnClick() {
  if (program === null || program.snakesLiving == 0) {
    resetProgram();
    initProgram();
  } else {
    program.halt();
    var stepsPerSecond = document.getElementById('steps-per-second');
    program.speed = +stepsPerSecond.innerHTML;
  }
  program.run();
}
function stepBtnClick() {
  if (program === null) {
    initProgram();
  } else {
    program.halt();
  }
  program.step();
}
function sourceDisplayClick() {
  resetProgram();
}
.container {
    width: 100%;
}
.so-box {
    font-family:'Helvetica Neue', Arial, sans-serif;
    font-weight: bold;
    color: #fff;
    text-align: center;
    padding: .3em .7em;
    font-size: 1em;
    line-height: 1.1;
    border: 1px solid #c47b07;
    -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
    text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
    background: #f88912;
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
    display: inline-block;
    border-radius: 6px;
    float: left;
    margin-right: 25px;
    cursor: pointer;
}
.option {
    padding: 10px 20px;
    margin-right: 25px;
    float: left;
}
h1 {
    text-align: center;
    font-family: Georgia, 'Times New Roman', serif;
}
a {
    text-decoration: none;
}
input, textarea {
    box-sizing: border-box;
}
textarea {
    display: block;
    white-space: pre;
    overflow: auto;
    height: 100px;
    width: 100%;
    max-width: 100%;
    min-height: 25px;
}
span[contenteditable] {
    padding: 2px 6px;
    background: #cc7801;
    color: #fff;
}
#stdout-container, #stdin-container {
    height: auto;
    padding: 6px 0;
}
#reset {
    float: right;
}
#source-display-wrapper , #stdin-display-wrapper{
    display: none;
    width: 100%;
    height: 100%;
    overflow: auto;
    border: 1px solid black;
    box-sizing: border-box;
}
#source-display , #stdin-display{
    font-family: monospace;
    white-space: pre;
    padding: 2px;
}
.activeToken {
    background: #f93;
}
.nextActiveToken {
    background: #bbb;
}
.swallowedCode{
    color: #999;
}
.clearfix:after {
    content:".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
.clearfix {
    display: inline-block;
}
* html .clearfix {
    height: 1%;
}
.clearfix {
    display: block;
}
<!--
Designed and written 2015 by D. Loscutoff
Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766
-->
<div class="container">
<textarea id="source" placeholder="Enter your program here" wrap="off">i.)o</textarea>
<div id="source-display-wrapper" onclick="sourceDisplayClick()"><div id="source-display"></div></div></div><div id="stdin-container" class="container">
<textarea id="stdin" placeholder="Input" wrap="off">Hello, World!</textarea>
<div id="stdin-display-wrapper" onclick="stdinDisplayClick()"><div id="stdin-display"></div></div></div><div id="controls-container" class="container clearfix"><input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /><input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /><input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /><input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /></div><div id="stdout-container" class="container"><textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea></div><div id="options-container" class="container"><div class="option so-box">Steps per Second:
<span id="steps-per-second" contenteditable>10</span></div></div>

DLosc

Posted 2015-10-30T16:16:15.190

Reputation: 21 213

4

ಠ_ಠ, 7 bytes

ಠ_ಠ

Try it now! ಠ_ಠ

This isn't even a code-golfing language.

Mama Fun Roll

Posted 2015-10-30T16:16:15.190

Reputation: 7 234

4

Seriously, 7 bytes

	W+	W+R

Hexdump (reversible with xxd -r):

00000000: 0957 2b09 572b 52                        .W+.W+R

Explanation (tabs are replaced with \t for clarity):

\tW+\tW+R
\t         read a single byte of input
  W+\tW    while TOS is truthy:
   +         append
    \t       read a single byte of input
       +R  append, reverse, and implicitly print

Try it online!

Mego

Posted 2015-10-30T16:16:15.190

Reputation: 32 998

1Link not found for IDE – phase – 2015-11-16T03:03:54.670

1just don't go breaking my heat – phase – 2015-11-16T03:06:17.677

Link is dead. Also, why do you swap the top two elements? Is it that there is an element other than the input byte? – Erik the Outgolfer – 2017-01-14T11:55:23.427

@EriktheOutgolfer Seriously is stack-based, so without swapping, the output would be reversed. – Mego – 2017-01-14T12:05:10.020

4

Piet, 3 codels

enter image description here

First Piet program! Quick explanation: input chars, output chars.

Mama Fun Roll

Posted 2015-10-30T16:16:15.190

Reputation: 7 234

4

Sesos, 1 byte

Y

This program handles both infinite streams and null bytes.

Try it online! Check Debug to see the generated binary code.

How it works

The binary file above has been generated by assembling the following SASM code.

set mask ; Switch to unsigned 8-bit cells.

         ; (implicit jmp)
         ;     Set an entry marker and jump to the jne instruction.
    put  ; Print the byte in the current cell to STDOUT.
jnz      ; (implicitly promoted to jne)
         ;     Read a byte from STDIN and save it in the current cell.
         ;     If EOF has not been hit, jump to the previous instruction.

Dennis

Posted 2015-10-30T16:16:15.190

Reputation: 196 637

How does set mask have anything to do with null bytes? – Erik the Outgolfer – 2016-10-05T16:31:22.243

set mask has nothing to do will null bytes. Using character-based I/O would only work with certain locales though. If the locale uses, e.g., UTF-8, an input consisting of a single 0xFF byte would error. – Dennis – 2016-10-05T16:38:53.233

3

Whitespace, 29 26 bytes


  
   
 
 	
	 				
  
 


Try it online!

Continuously reads a character from STDIN and outputs it to STDOUT. Unprintable characters including NUL bytes are handled like any other character, only EOF will terminate the program.

Explanation

(s - space, t - tab, n - newline)

nssn # Label ''
sssn # Push 0 - stack: [0]
sns  # Duplicate the top item on the stack - stack: [0, 0]
tnts # Pop, read a character from STDIN and place it at the address given by the popped value - stack: [0] heap: [0:<char>]
ttt  # Pop, push the heap value at the address given by the popped value - stack: [<char>]
tnss # Pop, output the popped value as a character to STDOUT - stack: []
nsnn # Jump to label ''

Ephphatha

Posted 2015-10-30T16:16:15.190

Reputation: 581

3

Pyramid Scheme, 199 116 bytes

Saved 83 bytes thanks to Khuldraeseth na'Barya! Clever idea to use the "nameless" variable, an empty triangle.

   ^
  /d\
 / o \
^-----^
-    ^-^
    ^-/ \
   ^-/out\
  / \-----^
 /set\    -
^-----^
-    /l\
    /ine\
    -----

Try it online!


Old version (functionally equivalent)

      ^
     / \
    /do \
   ^-----^
  /A\   / \
  ---  /   \
      /     \
     /       \
    ^---------^
   / \       / \
  /set\     /out\
 ^-----^   ^-----
/A\   /l\ /A\
---  /ine\---
     -----

Try it online!

Explanation

This might look like this in a scheme/lisp-like language:

(do (pair (set A read-line) (print A)) A)

Or, in a C-like language:

do {
    A = gets();
    puts(A);
} while(A);

Conor O'Brien

Posted 2015-10-30T16:16:15.190

Reputation: 36 228

125 bytes – Khuldraeseth na'Barya – 2019-07-25T18:24:31.547

116 – Khuldraeseth na'Barya – 2019-07-25T18:26:43.983

@Khuldraesethna'Barya Fascinating structure... Thanks! – Conor O'Brien – 2019-07-26T00:35:28.743

Can you add some documentation for this language? I would like to try it out – Jo King – 2019-07-26T06:23:45.760

1@JoKing Sure thing! I'm going off to bed rn, I'll add it to my todo list and I'll ping you once I'm done. – Conor O'Brien – 2019-07-26T06:24:39.223

3

Keg, 0 8 bytes

{?(,)\
,

Supports multi-line input now. Halts in an error, which is allowed by default

Try it Online!

EdgyNerd

Posted 2015-10-30T16:16:15.190

Reputation: 1 106

fixed (padding) – EdgyNerd – 2019-08-24T14:26:23.307

3

Befunge-93, 9 6 bytes

This solution (thanks to ninjalj!) depends on 0 % 0 throwing an error and halting, thus it will not work in all interpreters (like this one, where it's NaN instead and does not halt, though no more characters are outputted).

~:1+%,

~ reads in a character from input (-1 on EOF), then :1+ duplicates it and adds 1, so we now have either [0,0] or [n,n+1] on the stack. 0 % 0 is undefined, which (possibly) throws an error whereas n % (n+1) is simply n. , outputs as character.


Solution that does not depend on STDERR (9 bytes):

~:1+!#@_,

~ reads in a character from input (-1 on EOF), :1+ duplicates it and adds 1, ! "not"s this, then the # is a trampoline that jumps the program counter over the @. _ is a horizontal branch that goes right if the top of stack is 0, left otherwise. This is why I needed to ! the input + 1 earlier.


For what it's worth, you can try to get rid of the ! by reversing program flow. Unfortunately, to do this, you have to add a < and that simply produces another 9-byte solution:

<,_@#+1:~

El'endia Starman

Posted 2015-10-30T16:16:15.190

Reputation: 14 504

Using the stderr rule, you can golf it to 6 bytes: ~:1+%,. This trick is used a lot in golf.shinh.org – ninjalj – 2015-11-02T19:28:49.730

@ninjalj: Nice tip! Doesn't work in the Befunge interpreter I usually use though; 00% results in NaN. I'll include it anyway.

– El'endia Starman – 2015-11-02T19:53:45.197

3

Perl, 18 bytes

print while$_=getc

Will handle null bytes and infinite streams.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1Since the currently top answer consists of a sed invocation with no commands, you could also shorten this to perl -pe ''. However for the scope of the question your current solution is way more interesting, so if you do switch to the cheaty perl -pe '' please also leave your current solution. – kos – 2015-11-01T18:33:26.827

The problem with perl -pe '' is that it would only work if the input was finite or contained occasional newlines. By using getc it can handle an infinite stream of input without newlines. – BenGoldberg – 2017-01-14T17:02:28.693

3

C++, 65 61 bytes

#include<ios>
int main(){while(int i=~getchar())putchar(~i);}

Basically Dennis's C answer adapted for C++. g++ and clang++ give warnings, for me, but compile it just fine.

Saved some bytes thanks to Zereges!

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1I'm not surprised that clang is ringing warning bells. – Addison Crump – 2015-10-30T17:04:13.880

1Same amount of bytes, but if you change the second line to int main(){for(int i;i=~getchar();)putchar(~i);} you get one less warning. – user530873 – 2015-10-31T06:52:31.707

You can #include<ios> instead of <cstdio>. Also, change int main(int i){while(i=~getchar())putchar(~i);} to int main(){while(int i=~getchar())putchar(~i);}. It removes warnings and saves bytes. – Zereges – 2015-10-31T22:51:31.857

3

Retina, 3 1 byte



That's a single linefeed.

Try it online!

The empty Retina program would count the number of matches of the empty regex in the input, so it can't compete with rs and sed here. There are several ways to implement a cat program, the shortest being a Replace stage that doesn't actually replace anything.

Retina cannot handle infinite streams (as it waits for EOF before starting any processing).

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

3

Macaroni 0.0.2, 44 chars

label l print set s read map slice s 0 1 1 l

Explanation:

label l           "define a label, which we need later"
print set s read  "read a line, set the variable s to it, and print it"
map
  slice s 0 1 1   "get the first element of the array s"
                  "this returns an array of either length 0 (if s was originally
                   empty) or 1"
  l               "map the resulting array over label l—essentially a
                   conditional goto"

Doorknob

Posted 2015-10-30T16:16:15.190

Reputation: 68 138

3

PDP-11 Unix Assembly, 38 bytes binary

s: xor r0, r0;      / set r0 to 0 (stdin)
   sys read; b; 1;  / read one byte
   tst r0; beq e;   / check return value, goto e if zero.
   sys write; b; 1; / fortuitously, r0 = 1 here. write one byte.
   br s;            / go to loop start.
e: sys exit;        / exit [r0 = 0]
.bss
b: .=.+1

I'll assemble it later to show the binary output (I haven't golfed the source yet either), but with symbols stripped this should come out to 36 bytes compiled: a 16-byte a.out header, and 2 bytes per instruction word (10, including arguments to system calls).

Note that the use of one-byte reads is not to save space (.bss variables take no space in the binary), it is so that the byte count argument to write can be hardcoded.

The OG is much larger by comparison. By my count, 60 instruction words, so 128 bytes. Of course, it has to loop through files on the command line (the original purpose of cat).

The binary output:

0000000 000407 000026 000000 000002 000000 000000 000000 000001
0000020 074000 104403 000026 000001 005700 001404 104404 000026
0000040 000001 000766 104401
0000046

38 bytes, as promised.

Source golfed: 59 bytes

s:74000
sys 3;b;1
5700;beq e
sys 4;b;1
br s
e:sys 1
b:.=.+1

Since I left out .bss, this generates a slightly larger binary at 40 bytes even.

Random832

Posted 2015-10-30T16:16:15.190

Reputation: 796

3

Mathematica, 43 bytes

While[a=!=EndOfFile,Print[a=InputString[]]]

LegionMammal978

Posted 2015-10-30T16:16:15.190

Reputation: 15 731

2Uhh, I think you meant While[Echo[InputString[]]=!=EndOfFile] which has the same byte count, but can be shortened to While[Echo@InputString[]=!=EndOfFile] – Martin Ender – 2015-11-13T16:03:45.203

3

Ruby, 19 bytes

This one handles arbitrary input like a champ:

print while gets 1

Ruby, 1 byte

An empty program run with the p flag behaves almost exactly like cat, but doesn't print until it hits a newline or EOF:

$ touch cat.rb
$ yes | ruby -p cat.rb
y
y
y
y

(...)

Ruby, 9 bytes

Basically the same, but doesn't need the p flag to be entered from the command line:

#!ruby -p

Not the most exciting entry, but I thought it should be in the catalogue.

daniero

Posted 2015-10-30T16:16:15.190

Reputation: 17 193

1touch echo.rb; (while true; do echo -n a; done) | ruby -p echo.rb never flushes for me. – Lynn – 2015-10-31T00:04:41.803

1@Mauris never? You don't know that unless you've solved the halting problem (or it crashes?) :) Kidding, but omg this question is tl;dr. I'm sure you're right though. – daniero – 2015-10-31T00:14:19.750

@Mauris there, 19 byte solution even works with your infinite stream of a's :) – daniero – 2015-10-31T00:25:02.037

Ah, that one does the trick. Very cool! :) – Lynn – 2015-10-31T00:26:28.200

3

awk, 9 1 byte

(thanks to a suggestion rewrite in the comments by Mauris)

1

Example:

echo "hello\nworld" | awk '1'

user530873

Posted 2015-10-30T16:16:15.190

Reputation: 139

Does this/can awk handle infinite input? – Martin Ender – 2015-10-31T00:21:14.337

@MartinBüttner yes infact... yes | awk '{print$0}' – user530873 – 2015-10-31T00:23:39.940

2awk '1' works as a 1-byte solution. – Lynn – 2015-10-31T12:23:33.520

@Mauris awk 1 is a "shorter" still 1-byte solution. Quotes are useless here. – jlliagre – 2015-11-02T23:18:14.650

@smpl yes | awk '1' only works because yes outputs a newline after each "yes" and awk's default record separator is a newline. This doesn't work for streams that contain no newlines, like yes | tr -d \\n | ./my_cat in the question, so it doesn't qualify. – ThisSuitIsBlackNot – 2015-11-12T18:47:16.263

One workaround would be to use awk + GNU coreutils: fold -1 | awk -vORS= 1 – ThisSuitIsBlackNot – 2015-11-12T19:07:12.857

3

Marbelous, 11 bytes

00
\\/\]]!!

How it works.

The 00 is a language literal, it represents 0, but could be exchanged for any hexadecimal value in this case. On the first tick, this value will fall down and hit \\ which is a deflector and will shove the marble to the right.

/\ is a cloner, which puts one marble to the right, back onto the deflector, this creates an infinite loop. The second copy will be placed to the right. This copy will hit the ]] device, which fetches the first character on STDIN and outputs its ascii code below. This will put the resulting marble off the botom of the board ; any marble that falls off the board gets printed to STDOUT.

In case there is nothing on STDIN, the ]] device will push the input marble too the right. There it will trigger the !! device, which terminates the board.

overactor

Posted 2015-10-30T16:16:15.190

Reputation: 3 500

3

Perl 5, 11 + 1 (-p flag) = 12 bytes

perl -pe 'INIT{$/=\1}'

Sets the input record separator in an INIT block to work with infinite streams without newlines.

nwellnhof

Posted 2015-10-30T16:16:15.190

Reputation: 10 037

Is this version-dependent? I tried it with Strawberry 5.20.2 and it waited for newlines. – msh210 – 2015-11-02T22:11:56.073

@msh210 That's something different. On a terminal, stdin is usually line-buffered, so this behavior is completely normal (just like cat). – nwellnhof – 2015-11-03T13:59:13.620

Very cool! It's a shame you can't set this with -0. Also, -p only adds one byte, not two.

– ThisSuitIsBlackNot – 2015-11-12T18:41:11.957

@ThisSuitIsBlackNot This page says: "This supposes stuff needs no quoting to go in single quotes, or it would need more characters to escape. If not, either the escape characters are counted in as well, or you put the script in a file, and count the difference to perl -nl file.pl, which now includes the hyphen as well as one of the spaces." I removed the single quotes at the expense of a backslash. – nwellnhof – 2015-11-13T14:23:55.523

@nwellnhof That just means that if putting stuff in single quotes requires escaping things, you also have to count the escapes. For example, say"It's alive!" contains a single quote, so you can't put it inside single quotes without escaping. Your answer requires no escaping to go in single quotes, so it scores 11 bytes for the contents of the single quotes, and 1 byte for the -p flag, for 12 total. No need to remove the single quotes, and no need to count them. – ThisSuitIsBlackNot – 2015-11-13T15:20:08.640

3

Carrot (version: ^3), 3 1 bytes

#

Explanation of code:

Basically prints the input to the output. The caret ^ is not needed because we do not wish to use any commands. Every instance of # is replaced with the input.


Carrot cannot handle infinite output yet as # is the only way to get the input in a string format.

user41805

Posted 2015-10-30T16:16:15.190

Reputation: 16 320

3

Rail, 19 bytes

$'main'
@-i\
  \o-@

Rail is such a pain to golf... :D

This terminates with an error upon hitting EOF but handles null bytes and infinite streams without an issue.

The execution path starts from the $ going South-East. On - the train turns East, i reads a character. On \ the train turns South-East, and on - East again. @ reverses movement direction. The train now moves West, where o outputs the character again. \ turns the train North-West, - turns it West and @ reverses it once more. At this point we're in a loop between the two @, which terminates when i tries to read the end of the stream.

With a properly tail recursive interpreter, there is an 18-byte solution as well, but I can't currently test whether the reference implementation could handle it (which I doubt):

$'main'
 -io{main}

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

3

GOTO++, 80 bytes

§1
J=ENTRETONTEXTE()
GOTOPRINT()
GOTONONNULPOURLESNULS %1 entreestd@Fin() - *(1)

Well, GOTO++…As far as I can see, you can either read a line or a number but you can't read a string of a given length. Or just a character for that matter. So this program unfortunately needs linefeeds in its input if it is to ever output anything.

arjanen

Posted 2015-10-30T16:16:15.190

Reputation: 151

3

Templates Considered Harmful, 4 bytes

A<1>

This is a language which is executed by having the C++ compiler figure out the type of a typedef in a template. The language only supports finite input.

A<1> refers to the first argument of an anonymous function. All user-defined functions are anonymous. A program is implicitly wrapped in Fun<>, so it defines a function that returns its first argument, which is the input.

feersum

Posted 2015-10-30T16:16:15.190

Reputation: 29 566

3

Stack Cats, 0 bytes

The language cannot handle infinite input/output streams (since the program doesn't start until EOF is encountered, and output is printed from a finite memory source at the end of the program). It does handle null bytes.


Try it online!

This is not a case of "let's assign a random task to the empty program as a special case for golfing". Instead, the fact that this works is actually a result of several design decisions and is completely consistent with the overall language semantics.

Mainly, Stack Cats is a very pure reversible programming language, which means that every piece of code can be cleanly undone within the language. I/O does not fit within this model, because once you've printed something to STDOUT you can't undo it. In theory you could undo reading input by pushing it back to some buffer, but for symmetry reasons, input and output are treated the same. To make I/O work, we read all input at the beginning of the program and push it onto the initial stack, and at the end of the program, the contents of the final stack are printed to STDOUT.

Secondly, to undo any piece of code, we simply mirror it (reverse characters, swap all brackets and slashes). Furthermore, every program has to be symmetric itself. This implies that every even-length program is a valid cat program, provided it terminates, since even-length programs necessarily consist of some code together with the code that inverts it. It just so happens that the shortest even-length program is empty.

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

3

Gaot++, 171 bytes

bleeeeeeeeeeeet
bleeeet bleeeeeet
bleeeeeeeeeet bleeeet blet
bleeeeeeeeeeeet bleeeet blet
bleeeeeeeeeeeeet bleeeet blet
bleeeeeeeeeeeeet bleeeet blet
bleeeeeeeet bleeeeeet

Compressed: 12e 4e 6e 10e 4e 1e 12e 4e 1e 13e 4e 1e 13e 4e 1e 8e 6e

Try it online!

Explanation

X 4e 1e, where 1e (blet) is a nop, basically forms a pattern where if you go from left to right, X is executed, but not from right to left.

Alternatively, if you have X 4e Y, then X is executed when you go from left to right, and Y otherwise.

Leaky Nun

Posted 2015-10-30T16:16:15.190

Reputation: 45 011

Just a suggestion: use b instead of blet. Use b instead of 1e. I have tested it, and it works. – Erik the Outgolfer – 2016-10-30T09:17:36.820

3

Addict, 31 bytes

Addict is my new Turing-tarpit esolang, based on PRINDEAL. Addict has 5 commands: alias, decrement, increment, char, and take. See the GitHub repo for more details.

a I
 t c
 O
 d
a O
 c c
 I
 d
I

Test it online here!

This basically defines a loop which repeatedly inputs a charcode and outputs it, until EOF is reached. Ungolfed version:

a input  # Define a command `input` that does the following:
 t char  #   Set variable `char` to the next charcode in the input.
 output  #   If there is a next charcode, run command `output`.
 d       #   Otherwise, just exit.

a output # Define a command `output` that does the following:
 c char  #   Output variable `char` as a charcode.
 input   #   Attempt to input again.
 d       #   (This line never gets run.)

input  # Run command `input`.

ETHproductions

Posted 2015-10-30T16:16:15.190

Reputation: 47 880

3

05AB1E, 4 2 bytes (not working)

Try it online!

Golfed from 4 to 2 bytes thanks to @daHugLenny!

Explanation

|       Takes input as array separated by breaks
 »      Join input array by newline
        Implicitly print

Geno Racklin Asher

Posted 2015-10-30T16:16:15.190

Reputation: 466

1You can replace vy, with ». – acrolith – 2016-10-07T16:31:21.770

Doesn't I work? http://05ab1e.tryitonline.net/#code=SQ&input=c2FkZ3NkZmdnaDM0NQ

– Magic Octopus Urn – 2016-10-07T16:59:20.733

1@carusocomputing not for multiline input, unfortunately. – Geno Racklin Asher – 2016-10-07T17:00:54.923

1

@carusocomputing try it here.

– Geno Racklin Asher – 2016-10-07T17:01:39.937

I missed the multi-line part, good call. – Magic Octopus Urn – 2016-10-07T17:01:55.817

2crossed out 4 is still regular 4 ;( – acrolith – 2016-10-07T22:41:45.673

1Here's an even bigger violation of the spec. Double newline seems to halt the output entirely. – None – 2016-11-21T23:33:02.803

3

R, 14 bytes

Output stdin, nothing fancy.

cat(scan(,''))

If stdin consists solely of numbers, you can do it in 11 bytes with cat(scan()).

As far as I know, there's no way to handle infinite input.

rturnbull

Posted 2015-10-30T16:16:15.190

Reputation: 3 689

I think it should be cat(readLines()). The issue with scan is that it does not behave properly with whitespace. What do you think?

– JayCe – 2018-05-29T12:55:37.233

3

Brain-Flak, 0 + 3 = 3 bytes

Needs the -c flag.


Try it online!

This language cannot possibly handle infinite input streams.

This language absolutely always appends a trailing newline to the output.

In the original Ruby interpreter, the input is a command-line arg instead of a STDIN stream. The online interpreter seems to have been modified.

Erik the Outgolfer

Posted 2015-10-30T16:16:15.190

Reputation: 38 134

2

D, 65 71 68 bytes

import std.c.stdio;void main(){for(int c;c=~getchar,c;)putchar(~c);}

The original version couldn't handle infinitely long lines, but we should still do better than the existing D solution's 94 bytes, so here's the D version of Dennis' C solution.

std.c.stdio is deprecated in favor of core.stdc.stdio, as is this use of the comma operator, but both are still legal as of the current version.

Edit 2: Saved 3 bytes thanks to Zachary's suggestions

Ray

Posted 2015-10-30T16:16:15.190

Reputation: 1 488

Um, I don't think you need the parens after getchar. – Zacharý – 2016-11-26T17:08:30.743

You can save a byte by changing the int c;while(...) to for(int c;...;). – Zacharý – 2016-11-26T17:17:22.787

@ZacharyT Good call on both counts. Down to 68 bytes. – Ray – 2016-11-28T21:43:49.667

2

Casio FX-7000G, 3 bytes

Due to the low amount of storage, the calculator's programming mode used a tokenized language to save space. This makes it somewhat competitive for code-golf...

Program:

?→X

Explanation:

?       # Take input from user
 →X     # Store in variable X
        # Implicit: Print last value

Note that although this is 5 UTF-8 bytes, the calculator uses its own encoding to store this in 3.

FlipTack

Posted 2015-10-30T16:16:15.190

Reputation: 13 242

2

NewbieFuck, 4 bytes

[.,]

I guess this is non-competing I'm not aware of any working interpreter, but I found the spec online (esolangs.org).

If I understand correctly, this is the same as Brainfuck, but [ ... ] is actually do-while loop (always executes the first time).

So, although the Brainfuck answer needs to take input before entering the loop, ,[.,], this language can omit the first input and use [.,]

Note: as end of input is signified by 0 in brainfuck, this cannot handle null bytes. It will also prepend a null byte to the output.

FlipTack

Posted 2015-10-30T16:16:15.190

Reputation: 13 242

Why not do [,.] so that it doesn't prepend a null byte? – caird coinheringaahing – 2017-09-03T14:49:24.597

1Then it would append the Null EOF byte at the end, which just shifts the problem to the other end. – sundar - Reinstate Monica – 2018-07-08T17:44:27.730

2

Malbolge, 9,502 bytes

Full code here.

Only included here for the sake of completeness, not my code. Here is the author's page.

Rɪᴋᴇʀ

Posted 2015-10-30T16:16:15.190

Reputation: 7 410

Link to code is dead. – pppery – 2017-07-27T21:36:40.940

I believe this is the code: http://www.matthias-ernst.eu/malbolge/cat.mb

– 12Me21 – 2018-01-31T14:00:31.650

2

Evil, 4 bytes

mrwb

This language can only handle 1 character of input at a time.

m: Serves as a marking character for b.
r: Reads a single character from stdin and stores it in the accumulator.
w: Writes the value of the accumulator to stdout.
b: Searches backwards for m and continues execution from there.

(My) interpreter in C++ here: https://github.com/xprogram/esolot/tree/master/lang/evil

Original interpreter in Java here: http://web.archive.org/web/20070906133127/http://www1.pacific.edu/~twrensch/evil/evil.java

XavCo7

Posted 2015-10-30T16:16:15.190

Reputation: 274

2

Perl, 13 or 14 bytes, depending on whether -e counts

perl -pe'BEGIN{$/=\1}'

Although perl's -p switch normally reads a line at a time, and thus would require the input data either be finite, or have newlines in it, we can change the input record separator $/.

If $/ is reference to a number, it causes perl to read fixed length records.

This has to happen inside a BEGIN block, or else at least one newline would be required in the input.

BenGoldberg

Posted 2015-10-30T16:16:15.190

Reputation: 389

2

Lean Mean Bean Machine, 7 bytes

O
i
!
~

Marble spawns at O, i reads single character from STDIN to the marble's value, ! print's the marble's value as a Unicode character, ~ teleports the marble back up to the top.

Skidsdev

Posted 2015-10-30T16:16:15.190

Reputation: 9 656

2

Bash, 2 bytes

A less known(?) alternative to dd and cat itself:

m4

Try it online!

ბიმო

Posted 2015-10-30T16:16:15.190

Reputation: 15 345

2

Wumpus, 6 bytes

i=)
o%

Try it online!

Explanation

First, to understand the control flow, we'll need to look at the actual program grid. Wumpus uses a triangular grid, so characters are alternatingly placed in upward and downward triangles. Furthermore, as opposed to many other Fungeoids, Wumpus does not use a wrapping grid. Instead, the instruction pointer (IP) is reflected off the boundary of the grid. That leads to the following flow through the grid:

enter image description here

Hence, Wumpus simply loops through the entire code (going right to left on the second line), i.e.

i=)%o

A single loop iteration is simple enough:

i   Read one byte N from STDIN and push it to the stack. EOF gives -1.
=   Duplicate.
)   Increment. Gives 0 at EOF.
%   Compute N % (N+1). At EOF this ends the program due to the division by zero.
    Otherwise, this just results in N itself.
o   Print the byte to STDOUT.

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

How do you make these nice visualisations? – Jo King – 2018-02-12T04:59:34.843

1@JoKing I'm just scripting them up by hand in Mathematica. – Martin Ender – 2018-02-12T09:10:48.867

2

Gol><>, 2 bytes

credit to Jo King

io

Try it online!

Errors out on EOF. The error message goes to stderr.

How it works

io

i   Push an input char
 o  Pop and print; error if last input hit EOF
    Repeat indefinitely

Gol><>, 4 bytes

iE;o

Try it online!

No-error version.

How it works

iE;o

i     Push an input char
 E;   Halt on EOF
   o  Pop and print
      Repeat indefinitely

Bubbler

Posted 2015-10-30T16:16:15.190

Reputation: 16 616

2

Shakespeare Programming Language, 96 bytes

,.Ajax,.Page,.Act I:.Scene I:.[Exeunt][Enter Page and Ajax]Ajax:Open mind!Speak thy!Let usAct I!

Try it online!

Some nice and weird grammer. Terminates in an error.

Shakespeare Programming Language, 125 bytes

,.Ajax,.Page,.Act I:.Scene I:.[Exeunt][Enter Page and Ajax]Ajax:Open mind!Be you nicer a pig?If sospeak thy!If solet usAct I!

Try it online!

Non-erroring version. I especially liked constructing the sentence If solet usact I!

Jo King

Posted 2015-10-30T16:16:15.190

Reputation: 38 234

2

Grocery List, 14 bytes

*but it doesn't look like a grocery list

h

i
l
p
i
e
t

Explanation:

Title

i nput
l oop
p op and print
i nput
e nd loop if nonzero
t erminate

u_ndefined

Posted 2015-10-30T16:16:15.190

Reputation: 1 253

2

C, 17, 16 bytes

main(){tee(0,1);}

This only works on certain compilers (such as tutorialspoint which uses GCC), but it's really short.

main(){tee(1j);}

Edit: Now down to 16 bytes! j is a GNU suffix which acts as a complex
number. Basically tee(1j) == tee(0,1). This trick also only works in rare cases.

dingledooper

Posted 2015-10-30T16:16:15.190

Reputation: 421

2

Cascade, 7 6 bytes

?.
;,^

Basically works by going in a loop outputting an input character until EOF is reached

I didn't realise the starting point wasn't required, -1 byte

Try it online!

EdgyNerd

Posted 2015-10-30T16:16:15.190

Reputation: 1 106

This is actually the same as the example cat program I made. Nice work!

– Jo King – 2019-09-25T06:50:56.373

2

Python 3, 50 bytes

import sys
while 1:print(sys.stdin.read(1),end='')

See comment in my python 2 answer about newlines.

OR 29 bytes

while 1:print(input())

Waits explicitly for newlines before printing. (This means that it won't print anything after a newline before the next)

Blue

Posted 2015-10-30T16:16:15.190

Reputation: 26 661

1Adds trailing newline. – feersum – 2015-10-30T16:42:58.080

Can't you do print(end=sys.stdin.read(1))? – Erik the Outgolfer – 2016-09-27T17:52:08.507

I've found a shorter one using os.read/write and fd numbers, it is 42 bytes. https://tio.run/##K6gsycjPM/7/P60oP1chv1ghM7cgv6hEi6s8IzMnVaG8KLMkVcNQpyg1MUXDQMdQU9PK4P//ktTiEgA

– Rick Rongen – 2018-12-28T18:23:29.037

Feel free to post it yourself and take the credit for it^^ – Blue – 2018-12-28T18:32:24.053

2

C--, 171 bytes

target byteorder little;import getchar,putchar;export main;foreign"C"main(){t:bits32 v;v=foreign "C" getchar();if(v!=-1){foreign"C"putchar(v);goto t;}foreign"C"return(0);}

Considering C-- is essentially a "portable assembler", I shouldn't be surprised that this was huge.

kirbyfan64sos

Posted 2015-10-30T16:16:15.190

Reputation: 8 730

2

Befunge-98, 4 bytes

#@~,

The program counter starts moving to the right in the top-left corner of the program. # causes it to jump over @, landing on ~. This reads a character, or reflects the PC on EOF. If EOF is reached, this will cause it to run into @, which ends the program. Otherwise, it continues to ,, which prints the character that was read, and loops back to # thanks to Lahey-space.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

Is the reflect-on-EOF behavior in the spec? I didn't know about it before. (Then again, I coded mostly in Befunge-93.) – El'endia Starman – 2015-10-30T16:52:53.803

Yeah: In the case of an end-of-file or other file error condition, the & and ~ both act like r. – Lynn – 2015-10-30T16:53:34.773

Huh, interesting. The lack of this behavior in Befunge-93 added five bytes! Doubled the program length! – El'endia Starman – 2015-10-30T16:54:45.040

2

Pyth, 28 bytes

V$__import__('sys').stdin$pN

Not as short as @Mauris's Pyth answer, but it handles infinite input.

kirbyfan64sos

Posted 2015-10-30T16:16:15.190

Reputation: 8 730

2

Javascript, 25 23 22 bytes

for(;;)alert(prompt())

Edit: Thanks to stefnotch for saving 2 3 bytes

Shelvacu

Posted 2015-10-30T16:16:15.190

Reputation: 610

You could golf it like this: for(;;alert(prompt())); Here is a link that might help: http://codegolf.stackexchange.com/questions/2682/tips-for-golfing-in-javascript/

– Stefnotch – 2015-10-30T19:17:54.840

Just realized that you could have the function outside the loop, saving yet another byte for(;;)alert(prompt()) – Stefnotch – 2017-02-12T18:08:10.160

2

Erlang, 108 Bytes

Uses escript to run. Making the code a one-liner seems to cause an EOF error from the interpreter.

#!/usr/bin/env escript
main(_)->f(a).
f(eof)->ok;f([C])->f(io:format("~c",[C]));f(_)->f(io:get_chars('',1)).

Lloyd MacLea

Posted 2015-10-30T16:16:15.190

Reputation: 21

2

Julia, 45 bytes

while !eof(STDIN) print(read(STDIN,Char))end

Ungolfed + explanation:

while !eof(STDIN)             # While EOF has not been encountered from STDIN
    r = read(STDIN, Char)     # Read a single character from STDIN
    print(r)                  # Print it to STDOUT with no trailing anything
end

This supports an infinite input stream and null bytes and has no extraneous output.

Thanks to Dennis and Martin Büttner for their help on this!

Alex A.

Posted 2015-10-30T16:16:15.190

Reputation: 23 761

2

lua for windows, 38 bytes

Needs lua for windows

while true do io.write(io.read()) end

how it works

It prints the input from the terminal

Alex Allen

Posted 2015-10-30T16:16:15.190

Reputation: 91

2

D, 94 bytes

import std.stdio,std.algorithm;void main(){stdin.byChunk(1).copy(stdout.lockingTextWriter());}

I'm no D expert at all, so there might be a better way to do this.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

I don't think you need the parens after stdout.lockingTextWriter. – Zacharý – 2016-11-26T17:53:04.420

2

Emmental, 20 bytes

;#44#46#35#57#63#9!<tab>

The program ends with a tab character. This beats the example on the wiki page by redefining and invoking the tab character (ASCII 9) instead of the asterisk (ASCII 42). The spec doesn't really mention what , does at EOF, but the reference implementation uses getChar, which raises an IOError when the file ends. (The , is "quoted" as #44 in the above program.)

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

2

QBasic, 15 bytes

?INPUT$(1);
RUN

QBasic doesn't have any concept of input or output streams (except maybe where files are concerned). The above program instead takes any character you enter and echoes it to the screen, which I think fits the spirit of the challenge. RUN restarts the program from scratch, thus continuing to read and echo forever (there's no EOF for keyboard input, and I don't think it's even possible to enter a null byte).

Here's a 34-byte version that quits when you press escape. The should be replaced with a literal Esc character, ASCII 27. This can be entered in the QBasic editor by holding the Alt key while typing the character code; it shows up as a .

9?x$;
x$=INPUT$(1)
IF"…"<>x$THEN 9

DLosc

Posted 2015-10-30T16:16:15.190

Reputation: 21 213

2

PHP, 20 bytes

<? fpassthru(STDIN);

Kind of surprised there isn't one for PHP yet...

Niet the Dark Absol

Posted 2015-10-30T16:16:15.190

Reputation: 647

I bet you can get rid of the space. – Lynn – 2015-10-31T12:09:03.780

1Run it with -r and you can get rid of the opening tag altogether. echo -e "Hello\nWorld" | php -r 'fpassthru(STDIN);' 17 bytes – aross – 2016-03-18T10:51:20.457

2

ngn APL, 7 bytes

{∇⍞←⍞}1

ngn APL only supports linewise input and has no actual looping constructs, so this recursive function is as good as it gets. It prints null bytes, but only if they do not occur on the last line.

How it works

{    }   Define a function.
  ⍞←⍞    Read and print a line.
 ∇       Call the function again.
      1  Call the function with dummy input.

exits automatically on EOF.

Dennis

Posted 2015-10-30T16:16:15.190

Reputation: 196 637

There is the looping construct . It's just not so procedural. – jimmy23013 – 2015-11-01T23:51:32.857

I haven't been able to get working for this task. Anyway, -⍣≡1 leaks memory, so the result would probably be the same. – Dennis – 2015-11-02T04:44:25.210

2

Java, 120 bytes

The other Java solution is shorter than mine but, it uses Apache libraries to get the job done. I think it's worthwhile to put forward a java solution that relies solely on the java standard libraries.

This code works for infinite input and for input that contains null bytes.

class C{public static void main(String[]a)throws Exception{byte[]b={0};while(System.in.read(b)>=0)System.out.write(b);}}

Ungolfed

import java.io.IOException;

public class Cat {
  public static void main(String[] args) throws IOException {
    byte[] input=new byte[1];
    while(System.in.read(input)>=0){
      System.out.write(input);
    }
  }
}

ankh-morpork

Posted 2015-10-30T16:16:15.190

Reputation: 1 350

You don't need public in the class declaration. You can just throw Exception instead of IOException and not have to import anything in the Ungolfed version. – Addison Crump – 2015-11-02T11:35:35.013

Using the stderr rule, you could abuse an enum: enum C{C;System z;{try{byte[]b={0};while(z.in.read(b)>=0)z.out.write(b);}catch(Exception e){}}} – ninjalj – 2015-11-02T20:16:04.973

@ninjalj I can't figure out how to get the compiled class to execute the code block without loading the class from some other program. Is there anyway to execute it from the command line? – ankh-morpork – 2015-11-02T21:09:10.170

@dohaqatar7: java -classpath <wherever> C should work. – ninjalj – 2015-11-02T21:16:06.977

2

Groovy, 39 bytes

System.in.eachByte{System.out.write it}

Since I wrote a proof-of-concept to confirm that Groovy can handle infinite stream, might as well post it as an answer.

Usage:

groovy <script_name>

n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

Posted 2015-10-30T16:16:15.190

Reputation: 5 683

2

O, 7 bytes

1{io1}w

O is a new stack-based golfing language that aims to have as many 1-byte commands as possible. You can find O on GitHub.

1: pushes 1 for a truthy value.

{: begin code block (like ruby)

i: pushes input to stack

o: outputs top of stack

1: as above

}: ends code block

w: repeatedly does code block immediately before it while top of stack is truthy (pops top of stack)

Hipe99

Posted 2015-10-30T16:16:15.190

Reputation: 87

"aims to have as many 1-byte commands as possible"... so, it's Pyth or APL or CJam? – Sparr – 2015-11-14T08:35:28.080

@Sparr More like GS2 or Seriously. – Martin Ender – 2015-11-14T08:42:34.857

2

Emotinomicon, 29 bytes

⏪⏫⏬➕⁉️⏩

Most of the program is just checking for EOF.

LegionMammal978

Posted 2015-10-30T16:16:15.190

Reputation: 15 731

2

LabVIEW, 3 LabVIEW Primitives

Pretty obvious what it does I would say.

Eumel

Posted 2015-10-30T16:16:15.190

Reputation: 2 487

2

Samau, 0 bytes

An empty program in Samau is a cat program. It simply pushes the input onto the stack as a string, and prints the top of the stack.

Since Samau is written in Haskell, it can handle infinite streams.

alephalpha

Posted 2015-10-30T16:16:15.190

Reputation: 23 988

2

PlatyPar, 0 bytes

 

Try it online

At the beginning of the program, input is implicitly pushed to the stack. At the end of the program, the stack is implicitly printed.

Cyoce

Posted 2015-10-30T16:16:15.190

Reputation: 2 690

2

Emotinomicon, 5 chars / 15 bytes

⏫⏪⏬⏫⏩

Press "cancel" to exit the loop. Try it here!

⏫   ⏪   ⏬   ⏫   ⏩   explanation
⏫                   take one character as input, push it to the stack
    ⏪               open loop
        ⏬           pops and outputs top of stack as character
            ⏫       take one character as input, push it to the stack
                ⏩   close loop

Conor O'Brien

Posted 2015-10-30T16:16:15.190

Reputation: 36 228

Would ⏪⏫⏬⏩ work? – Pavel – 2016-11-18T20:54:32.720

@Pavel no it would not, since the stack would be falsey being empty and thus the loop would end. – Conor O'Brien – 2016-11-18T20:56:56.130

2

NTFJ, 4 bytes

(*~^

An online interpreter can be found here.

NTFJ is an esoteric programming language, made by user @ConorO'Brien, intended to be a Turing tarpit. It is stack-based, and pushes bits to the stack, which can be later coalesced to an 8-bit number. The bytes of the input are pushed to the stack before the program is run, with the first byte on top. This particular program is fairly simple:

(      If top of stack is not 0:
 *      Pop byte, output as a character.
  ~     Push 0.
   ^    Pop bit/byte and jump to the instruction at the corresponding index.
        This moves us back to the beginning of the program, which is thus looped until the stack is empty.

ETHproductions

Posted 2015-10-30T16:16:15.190

Reputation: 47 880

Try chopping off the last paren, it should still work. – Conor O'Brien – 2016-03-02T19:42:12.160

@CᴏɴᴏʀO'Bʀɪᴇɴ Thanks, it does indeed! – ETHproductions – 2016-03-15T20:04:36.723

+1 for the emote: *~^ – user48538 – 2016-03-16T08:08:05.203

2

Gogh, 0 bytes

 

This is functional in a Gogh program with input.


Usage

$ ./gogh <standard-flags> <code-or-path> <input>

In this case:

$ ./gogh o "" <input>

Zach Gates

Posted 2015-10-30T16:16:15.190

Reputation: 6 152

2

CoffeeScript/LiveScript/etc. (Node.js), 31 bytes

I'm not sure if any of those languages have been used yet, but here it is.

p=process;p.stdin.pipe p.stdout

Because it takes advantage of so few features, most of the CoffeeScript descendants with any notability would work with this code, including LiveScript, Coco, and IcedCoffeeScript.

Oh, and it does deal with infinite streams.

Isiah Meadows

Posted 2015-10-30T16:16:15.190

Reputation: 1 546

2

0815, 10 bytes

(interpreter, don't let the pirate icon scare you)

}: :!~$^: 

Note that there is a trailing space at the end. This one survives trimmers:

}:0:!~$^:0

They work the same.

Explanation

0815 has three memory registers: X, Y and Z. X is write-able, Z is read-able. Y cannot be directly accessed, but only with rotations. At start, X is 0x0, Y is 0x0 and Z is 0x0. 0815 only supports hexadecimal numbers. Labels point to a specific part in the code: the character after their definition. Here are the symbols used here:

  • } : :: } defines a label, : starts its parameter (the label), is the label, and : closes the parameter, thus creating the label at this point (char 5).
  • !: ! gets a byte from STDIN and stores it in X.
  • ~ $: ~ is needed to rotate left, so that X is Y, Y is Z and Z is X. Then, $ is used to print the character in Z to the screen.
  • ^ : : ^ jumps to the label specified if Z is not 0x0. Note that closing is not required on this step, as this is the end of the program. This allows an un-copiable null byte to be printed.

Erik the Outgolfer

Posted 2015-10-30T16:16:15.190

Reputation: 38 134

2

Seed, 7 Bytes

2 20093

Seed is a language which generates Befunge-93 with a length and a random seed. 2 is the length and 20093 is the random seed.

Mega Man

Posted 2015-10-30T16:16:15.190

Reputation: 1 379

And the byte count is...? – user48538 – 2016-07-16T06:46:02.773

2

Gaot++, 113 bytes

bleeeet bleeeeeet bleeeeeeeeeeeet bleeeet b bleeeeeeeeeeeeet bleeeet b bleeeeeeet bleeeet bleeeeeeeeeet bleeeeeet

In Compressed Gaot++ it's 25 bytes:

4e6e12e4eb13e4eb7e4e10e6e

Cannot terminate on the offline interpreter, EOF is not recognized by the language :(

Online interpreter for both normal and compressed versions.

Erik the Outgolfer

Posted 2015-10-30T16:16:15.190

Reputation: 38 134

Shall I create a verbal representation of this? – tuskiomi – 2016-11-18T21:17:51.947

1@tuskiomi What do you mean? Those are surely screaming gaots! – Erik the Outgolfer – 2016-11-18T21:47:17.180

1

Arcyóu, 2 bytes

(q

Try it online!

Strange, a search for arcyóu inquestion:62230 doesn't seem to turn anything up.

Arcyóu has a strange behavior: if there isn't a trailing newline in the output, it will unavoidably append one. If there is a trailing newline, another one will not be appended. (p(q will not fix the problem, it will just forcibly append another \n.

This language cannot possibly handle infinite input.

Arcyóu is weird.

First Arcyóu answer of mine :D

Erik the Outgolfer

Posted 2015-10-30T16:16:15.190

Reputation: 38 134

1

Actually, 6 bytes

○W◙○WX

Try it online!

+2 bytes because I fixed the trailing newline issue.

Erik the Outgolfer

Posted 2015-10-30T16:16:15.190

Reputation: 38 134

1

tcl, 17

puts [read stdin]

available to run on http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMeHVzQWNwMjZGZVk

To stop it from running, press Ctrl+D.

sergiol

Posted 2015-10-30T16:16:15.190

Reputation: 3 055

1

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

smls

Posted 2015-10-30T16:16:15.190

Reputation: 4 352

1

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

MildlyMilquetoast

Posted 2015-10-30T16:16:15.190

Reputation: 2 907

1

SmileBASIC, 13 bytes

LINPUT S$?S$;

very simple.

12Me21

Posted 2015-10-30T16:16:15.190

Reputation: 6 110

1

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

Phlarx

Posted 2015-10-30T16:16:15.190

Reputation: 1 366

1

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!

Sp3000

Posted 2015-10-30T16:16:15.190

Reputation: 58 729

1

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

L3viathan

Posted 2015-10-30T16:16:15.190

Reputation: 3 151

1

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.

L3viathan

Posted 2015-10-30T16:16:15.190

Reputation: 3 151

1

Python 2, 28 bytes

while 1:
 print(raw_input())

Try it online!

LMD

Posted 2015-10-30T16:16:15.190

Reputation: 377

Quite sure someone has tried that already. This is not gonna work for infinite input (without newline) :/ – daniero – 2017-05-27T16:13:41.357

@daniero : Edited it. – LMD – 2017-05-27T17:27:26.397

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 – 2017-05-27T17:34:37.783

1

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.

Robert Fraser

Posted 2015-10-30T16:16:15.190

Reputation: 912

1

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.

MD XF

Posted 2015-10-30T16:16:15.190

Reputation: 11 605

1

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.

TuxCrafting

Posted 2015-10-30T16:16:15.190

Reputation: 4 547

1

Foam, 5 bytes

,* ."

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

Esolanging Fruit

Posted 2015-10-30T16:16:15.190

Reputation: 13 542

1

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.

pppery

Posted 2015-10-30T16:16:15.190

Reputation: 3 987

1

Unwanted, Unnecessary, Opportunistic, 0 bytes


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

faso

Posted 2015-10-30T16:16:15.190

Reputation: 141

1

Emmental, 24 bytes

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

ABot

Posted 2015-10-30T16:16:15.190

Reputation: 203

1

Caker, 10 bytes

ωΩ(ξΘ)

(uses UTF-8)

ABot

Posted 2015-10-30T16:16:15.190

Reputation: 203

1

Zucchini, 74 bytes

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

ABot

Posted 2015-10-30T16:16:15.190

Reputation: 203

1

Cubically, 13 12 bytes

(~-1/1=&6@7)

Cubically can finally do this! Yay! We've been working on adding input/conditionals/loops for a while and just got it finished. Explanation:

(             open loop (can be looped unconditionally)
 ~            read character as input
  -1/1        set notepad to -1 (EOF)
      =       compare with input buffer (implicit = defaults to =7)
       &6     if truthy, quit
         @7   print character
           )  loop infinitely

Try it online!

MD XF

Posted 2015-10-30T16:16:15.190

Reputation: 11 605

:0 is unnecessary because it will exit the program if the notepad is ever set to anything but 0 – TehPers – 2017-08-04T18:51:52.343

@TehPers Oh, didn't notice! Thanks – MD XF – 2017-08-04T18:52:43.210

1

Ly, 4 bytes

&i&o

Try it online!

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

LyricLy

Posted 2015-10-30T16:16:15.190

Reputation: 3 313

1

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.

MD XF

Posted 2015-10-30T16:16:15.190

Reputation: 11 605

1

;#*:), 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

caird coinheringaahing

Posted 2015-10-30T16:16:15.190

Reputation: 13 702

1

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.

Zongor

Posted 2015-10-30T16:16:15.190

Reputation: 51

1

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]);

Taylor Scott

Posted 2015-10-30T16:16:15.190

Reputation: 6 709

1Do you need to test if it is a formula first? It seems to work for plain text with '[A1].Formula' – seadoggie01 – 2018-09-07T16:02:58.883

1

Thotpatrol, 119 bytes

JACKING IN
DM THAUGHTY JO
  JO
  JO
REPORT UNPATRIOTIC ACTIVITY

Thotpatrol does not support support key-events outside of console input, so this is the most correct solution.

Link to implementation: https://github.com/MindyGalveston/thotpatrol-

Mr. Negi

Posted 2015-10-30T16:16:15.190

Reputation: 75

1

Nhohnhehr, 41 bytes

+----+
| /0\|
|$?@\|
| \1\|
|   #|
+----+

Try it online!

Erik the Outgolfer

Posted 2015-10-30T16:16:15.190

Reputation: 38 134

1

Whispers, 22 bytes

> InputAll
>> Output 1

Try it online!

caird coinheringaahing

Posted 2015-10-30T16:16:15.190

Reputation: 13 702

1

Funky, 28 bytes

io.stdin().pipe(io.stdout())

Shouldn't be too surprising. Just pipes STDIN to STDOUT.

Try it online!

ATaco

Posted 2015-10-30T16:16:15.190

Reputation: 7 898

1

Rust, 59 bytes

use std::io::*;fn main(){copy(&mut stdin(),&mut stdout());}

A glob import can be used to shorten previous Rust solution.

Konrad Borowski

Posted 2015-10-30T16:16:15.190

Reputation: 11 185

1

Icon, 40 bytes

procedure main()
while write(read())
end

Try it online!

ovs

Posted 2015-10-30T16:16:15.190

Reputation: 21 408

1

Ly, 16 bytes

Posting because I didn't know that &i existed when I did this.

i[&oi[r91+r&oi]]

Demo

weatherman115

Posted 2015-10-30T16:16:15.190

Reputation: 605

1

Pepe, 8 bytes

REEeReee

Try it online!

Explanation

Simple.

REEe     - Get all input as string
    Reee - Print all input

RedClover

Posted 2015-10-30T16:16:15.190

Reputation: 719

You could change your code to REEeReee because numbers will print char code – u_ndefined – 2018-07-11T06:32:32.550

@u_ndefined Oh, you're right. Fixed it, thanks. – RedClover – 2018-07-11T13:12:37.957

1

2DFuck, 79 bytes

!x>>>>>>>>vxvx[^^r![<r!]v![,x>r!]^![<r!]vr![>r!]vr![^^r![<r!]vv![^r.x>vr!]<]r!]

Try it online!

Explanation:

!x>>>>>>>>vxvx         Set [0|0], [8|1], [8|2] to true
[                      While the accumulator is true:
    ^^r![<r!]v           Go back to [0|1]
    ![,x>r!]             Read rightwards until first 1 ([8|1]) -> 8 bits
    ^![<r!]v             Go back to [0|1]
    r![>r!]              Find first one bit. This is [8|1] if we get a null byte (EOF)
    vr![                 If the bit below is 0:
        ^^r![<r!]v         Go back to [0|1]
        v![^r.x>vr!]<      Print everything til the first 1 in row 2 ([8|2]),
                             clearing all bits on row 1 before it. Stop at [7|2]
    ]r!                  Read and flip (so, exit if we have a 1 -> null byte)
]

wastl

Posted 2015-10-30T16:16:15.190

Reputation: 3 089

1

Ahead, 6 bytes

~oi@j~

~ causes the head to ignore all commands and keep moving until it encounters another ~. This means the head moves to the right edge of the board at the beginning. It then bounces off the edge and begins traveling left on its next movement step. When the head goes back to the left side and encounters the ~, it bounces off the left edge and travels right, skipping cells, and the cycle continues.

Try it online!

~  keep moving, ignoring commands until next ~
o  pop and print character
i  read character from stdin, bounce back if no input
@  end program
j  skip next cell
~

snail_

Posted 2015-10-30T16:16:15.190

Reputation: 1 982

1

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.

Yhprum

Posted 2015-10-30T16:16:15.190

Reputation: 51

1

Scratch (scratchblocks2), 40 bytes

when gf clicked
ask[]and wait
say(answer

Silas Reel

Posted 2015-10-30T16:16:15.190

Reputation: 111

1

Clojure, 19 bytes

(print(slurp *in*))

Try it online!

TheGreatGeek

Posted 2015-10-30T16:16:15.190

Reputation: 111

1

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

MilkyWay90

Posted 2015-10-30T16:16:15.190

Reputation: 2 264

1

Brainflub, 3 bytes

 *|

Explanation

: takes user input

* : outputs contents of stdin

| : ends program

Compiler

snorepion

Posted 2015-10-30T16:16:15.190

Reputation: 43

1

Turing Machine But Way Worse, 419 bytes

0 0 0 1 1 0 0
1 0 1 1 A 0 0
0 1 0 1 2 0 0
1 1 1 1 a 0 0
0 2 0 1 3 0 0
1 2 1 1 b 0 0
0 3 0 1 4 0 0
1 3 1 1 c 0 0
0 4 0 1 5 0 0
1 4 1 1 d 0 0
0 5 0 1 6 0 0
1 5 1 1 e 0 0
0 6 0 1 7 0 0
1 6 1 1 f 0 0
0 7 0 1 7 0 1
1 7 1 1 7 0 1
0 A 0 1 a 0 0
1 A 1 1 a 0 0
0 a 0 1 b 0 0
1 a 1 1 b 0 0
0 b 0 1 c 0 0
1 b 1 1 c 0 0
0 c 0 1 d 0 0
1 c 1 1 d 0 0
0 d 0 1 e 0 0
1 d 1 1 e 0 0
0 e 0 1 f 0 0
1 e 1 1 f 0 0
0 f 0 1 0 1 0
1 f 1 1 0 1 0

Try it online!

Full cat program.

u_ndefined

Posted 2015-10-30T16:16:15.190

Reputation: 1 253

Your efforts to make this answer have been modified to solve this challenge. Thought I'd let you know

– MilkyWay90 – 2019-07-31T16:45:19.627

1

1+, 13 bytes

1##,";1+1<1+#

Assuming EOF returns 0.

If error-terminating is allowed, it becomes fairly trivial:

1+, 7 bytes

1##,;1#

HighlyRadioactive

Posted 2015-10-30T16:16:15.190

Reputation: 1 585

1

Turing Machine Language, 7148 bytes

0 * * l 2 ;
1 _ _ l 2 ;
2 _ ( r 3 ;
3 _ _ r 4 ;
4 _ _ l 3) ;
4 * * r 2 ;
3) _ ) l 5 ;
3 * * r 3 ;
5 ( ( * 0 ;
5 * * l 5 ;
6 _ _ l 7 ;
7 _ ] r 8 ;
8 ) ) l 9 ;
8 * * r 8 ;
9 0 @ l c0 ;
9 1 @ l c1 ;
9 2 @ l c2 ;
9 3 @ l c3 ;
9 4 @ l c4 ;
9 5 @ l c5 ;
9 6 @ l c6 ;
9 7 @ l c7 ;
9 8 @ l c8 ;
9 9 @ l c9 ;
9 a @ l a ;
9 A @ l A ;
9 b @ l b ;
9 B @ l B ;
9 c @ l c ;
9 C @ l C ;
9 d @ l d ;
9 D @ l D ;
9 e @ l e ;
9 E @ l E ;
9 f @ l f ;
9 F @ l F ;
9 g @ l g ;
9 G @ l G ;
9 h @ l h ;
9 H @ l H ;
9 i @ l i ;
9 I @ l I ;
9 j @ l j ;
9 J @ l J ;
9 k @ l k ;
9 K @ l K ;
9 l @ l l ;
9 L @ l L ;
9 m @ l m ;
9 M @ l M ;
9 n @ l n ;
9 N @ l N ;
9 o @ l o ;
9 O @ l O ;
9 p @ l p ;
9 P @ l P ;
9 q @ l q ;
9 Q @ l Q ;
9 r @ l r ;
9 R @ l R ;
9 s @ l s ;
9 S @ l S ;
9 t @ l t ;
9 T @ l T ;
9 u @ l u ;
9 U @ l U ;
9 v @ l v ;
9 V @ l V ;
9 w @ l w ;
9 W @ l W ;
9 x @ l x ;
9 X @ l X ;
9 y @ l y ;
9 Y @ l Y ;
9 z @ l z ;
9 Z @ l Z ;
c0 ] ] l c0a ;
c0 * * l c0 ;
c0a _ 0 r @0 ;
c0a * * l c0a ;
@0 @ 0 l nC ;
@0 * * r @0 ;
c1 ] ] l c1a ;
c1 * * l c1 ;
c1a _ 1 r @1 ;
c1a * * l c1a ;
@1 @ 1 l nC ;
@1 * * r @1 ;
c2 ] ] l c2a ;
c2 * * l c2 ;
c2a _ 2 r @2 ;
c2a * * l c2a ;
@2 @ 2 l nC ;
@2 * * r @2 ;
c3 ] ] l c3a ;
c3 * * l c3 ;
c3a _ 3 r @3 ;
c3a * * l c3a ;
@3 @ 3 l nC ;
@3 * * r @3 ;
c4 ] ] l c4a ;
c4 * * l c4 ;
c4a _ 4 r @4 ;
c4a * * l c4a ;
@4 @ 4 l nC ;
@4 * * r @4 ;
c5 ] ] l c5a ;
c5 * * l c5 ;
c5a _ 5 r @5 ;
c5a * * l c5a ;
@5 @ 5 l nC ;
@5 * * r @5 ;
c6 ] ] l c6a ;
c6 * * l c6 ;
c6a _ 6 r @6 ;
c6a * * l c6a ;
@6 @ 6 l nC ;
@6 * * r @6 ;
c7 ] ] l c7a ;
c7 * * l c7 ;
c7a _ 7 r @7 ;
c7a * * l c7a ;
@7 @ 7 l nC ;
@7 * * r @7 ;
c8 ] ] l c8a ;
c8 * * l c8 ;
c8a _ 8 r @8 ;
c8a * * l c8a ;
@8 @ 8 l nC ;
@8 * * r @8 ;
c9 ] ] l c9a ;
c9 * * l c9 ;
c9a _ 9 r @9 ;
c9a * * l c9a ;
@9 @ 9 l nC ;
@9 * * r @9 ;
a ] ] l aa ;
a * * l a ;
aa _ a r @a ;
aa * * l aa ;
@a @ a l nC ;
@a * * r @a ;
A ] ] l Aa ;
A * * l A ;
Aa _ A r @A ;
Aa * * l Aa ;
@A @ A l nC ;
@A * * r @A ;
b ] ] l ba ;
b * * l b ;
ba _ b r @b ;
ba * * l ba ;
@b @ b l nC ;
@b * * r @b ;
B ] ] l Ba ;
B * * l B ;
Ba _ B r @B ;
Ba * * l Ba ;
@B @ B l nC ;
@B * * r @B ;
c ] ] l ca ;
c * * l c ;
ca _ c r @c ;
ca * * l ca ;
@c @ c l nC ;
@c * * r @c ;
C ] ] l Ca ;
C * * l C ;
Ca _ C r @C ;
Ca * * l Ca ;
@C @ C l nC ;
@C * * r @C ;
d ] ] l da ;
d * * l d ;
da _ d r @d ;
da * * l da ;
@d @ d l nC ;
@d * * r @d ;
D ] ] l Da ;
D * * l D ;
Da _ D r @D ;
Da * * l Da ;
@D @ D l nC ;
@D * * r @D ;
e ] ] l ea ;
e * * l e ;
ea _ e r @e ;
ea * * l ea ;
@e @ e l nC ;
@e * * r @e ;
E ] ] l Ea ;
E * * l E ;
Ea _ E r @E ;
Ea * * l Ea ;
@E @ E l nC ;
@E * * r @E ;
f ] ] l fa ;
f * * l f ;
fa _ f r @f ;
fa * * l fa ;
@f @ f l nC ;
@f * * r @f ;
F ] ] l Fa ;
F * * l F ;
Fa _ F r @F ;
Fa * * l Fa ;
@F @ F l nC ;
@F * * r @F ;
g ] ] l ga ;
g * * l g ;
ga _ g r @g ;
ga * * l ga ;
@g @ g l nC ;
@g * * r @g ;
G ] ] l Ga ;
G * * l G ;
Ga _ G r @G ;
Ga * * l Ga ;
@G @ G l nC ;
@G * * r @G ;
h ] ] l ha ;
h * * l h ;
ha _ h r @h ;
ha * * l ha ;
@h @ h l nC ;
@h * * r @h ;
H ] ] l Ha ;
H * * l H ;
Ha _ H r @H ;
Ha * * l Ha ;
@H @ H l nC ;
@H * * r @H ;
i ] ] l ia ;
i * * l i ;
ia _ i r @i ;
ia * * l ia ;
@i @ i l nC ;
@i * * r @i ;
I ] ] l Ia ;
I * * l I ;
Ia _ I r @I ;
Ia * * l Ia ;
@I @ I l nC ;
@I * * r @I ;
j ] ] l ja ;
j * * l j ;
ja _ j r @j ;
ja * * l ja ;
@j @ j l nC ;
@j * * r @j ;
J ] ] l Ja ;
J * * l J ;
Ja _ J r @J ;
Ja * * l Ja ;
@J @ J l nC ;
@J * * r @J ;
k ] ] l ka ;
k * * l k ;
ka _ k r @k ;
ka * * l ka ;
@k @ k l nC ;
@k * * r @k ;
K ] ] l Ka ;
K * * l K ;
Ka _ K r @K ;
Ka * * l Ka ;
@K @ K l nC ;
@K * * r @K ;
l ] ] l la ;
l * * l l ;
la _ l r @l ;
la * * l la ;
@l @ l l nC ;
@l * * r @l ;
L ] ] l La ;
L * * l L ;
La _ L r @L ;
La * * l La ;
@L @ L l nC ;
@L * * r @L ;
m ] ] l ma ;
m * * l m ;
ma _ m r @m ;
ma * * l ma ;
@m @ m l nC ;
@m * * r @m ;
M ] ] l Ma ;
M * * l M ;
Ma _ M r @M ;
Ma * * l Ma ;
@M @ M l nC ;
@M * * r @M ;
n ] ] l na ;
n * * l n ;
na _ n r @n ;
na * * l na ;
@n @ n l nC ;
@n * * r @n ;
N ] ] l Na ;
N * * l N ;
Na _ N r @N ;
Na * * l Na ;
@N @ N l nC ;
@N * * r @N ;
o ] ] l oa ;
o * * l o ;
oa _ o r @o ;
oa * * l oa ;
@o @ o l nC ;
@o * * r @o ;
O ] ] l Oa ;
O * * l O ;
Oa _ O r @O ;
Oa * * l Oa ;
@O @ O l nC ;
@O * * r @O ;
p ] ] l pa ;
p * * l p ;
pa _ p r @p ;
pa * * l pa ;
@p @ p l nC ;
@p * * r @p ;
P ] ] l Pa ;
P * * l P ;
Pa _ P r @P ;
Pa * * l Pa ;
@P @ P l nC ;
@P * * r @P ;
q ] ] l qa ;
q * * l q ;
qa _ q r @q ;
qa * * l qa ;
@q @ q l nC ;
@q * * r @q ;
Q ] ] l Qa ;
Q * * l Q ;
Qa _ Q r @Q ;
Qa * * l Qa ;
@Q @ Q l nC ;
@Q * * r @Q ;
r ] ] l ra ;
r * * l r ;
ra _ r r @r ;
ra * * l ra ;
@r @ r l nC ;
@r * * r @r ;
R ] ] l Ra ;
R * * l R ;
Ra _ R r @R ;
Ra * * l Ra ;
@R @ R l nC ;
@R * * r @R ;
s ] ] l sa ;
s * * l s ;
sa _ s r @s ;
sa * * l sa ;
@s @ s l nC ;
@s * * r @s ;
S ] ] l Sa ;
S * * l S ;
Sa _ S r @S ;
Sa * * l Sa ;
@S @ S l nC ;
@S * * r @S ;
t ] ] l ta ;
t * * l t ;
ta _ t r @t ;
ta * * l ta ;
@t @ t l nC ;
@t * * r @t ;
T ] ] l Ta ;
T * * l T ;
Ta _ T r @T ;
Ta * * l Ta ;
@T @ T l nC ;
@T * * r @T ;
u ] ] l ua ;
u * * l u ;
ua _ u r @u ;
ua * * l ua ;
@u @ u l nC ;
@u * * r @u ;
U ] ] l Ua ;
U * * l U ;
Ua _ U r @U ;
Ua * * l Ua ;
@U @ U l nC ;
@U * * r @U ;
v ] ] l va ;
v * * l v ;
va _ v r @v ;
va * * l va ;
@v @ v l nC ;
@v * * r @v ;
V ] ] l Va ;
V * * l V ;
Va _ V r @V ;
Va * * l Va ;
@V @ V l nC ;
@V * * r @V ;
w ] ] l wa ;
w * * l w ;
wa _ w r @w ;
wa * * l wa ;
@w @ w l nC ;
@w * * r @w ;
W ] ] l Wa ;
W * * l W ;
Wa _ W r @W ;
Wa * * l Wa ;
@W @ W l nC ;
@W * * r @W ;
x ] ] l xa ;
x * * l x ;
xa _ x r @x ;
xa * * l xa ;
@x @ x l nC ;
@x * * r @x ;
X ] ] l Xa ;
X * * l X ;
Xa _ X r @X ;
Xa * * l Xa ;
@X @ X l nC ;
@X * * r @X ;
y ] ] l ya ;
y * * l y ;
ya _ y r @y ;
ya * * l ya ;
@y @ y l nC ;
@y * * r @y ;
Y ] ] l Ya ;
Y * * l Y ;
Ya _ Y r @Y ;
Ya * * l Ya ;
@Y @ Y l nC ;
@Y * * r @Y ;
z ] ] l za ;
z * * l z ;
za _ z r @z ;
za * * l za ;
@z @ z l nC ;
@z * * r @z ;
Z ] ] l Za ;
Z * * l Z ;
Za _ Z r @Z ;
Za * * l Za ;
@Z @ Z l nC ;
@Z * * r @Z ;
Sp ] ] l Sp1 ;
Sp * * l Sp ;
Sp1 _ ~ r @Sp ;
Sp1 * * l Sp1 ;
@Sp @ _ l nC ;
@Sp * * r @Sp ;
nC _ @ l Sp ;
nC 0 0 * 9 ;
nC 1 1 * 9 ;
nC 2 2 * 9 ;
nC 3 3 * 9 ;
nC 4 4 * 9 ;
nC 5 5 * 9 ;
nC 6 6 * 9 ;
nC 7 7 * 9 ;
nC 8 8 * 9 ;
nC 9 9 * 9 ;
nC - - * 9 ;
nC a a * 9 ;
nC A A * 9 ;
nC b b * 9 ;
nC B B * 9 ;
nC c c * 9 ;
nC C C * 9 ;
nC d d * 9 ;
nC D D * 9 ;
nC e e * 9 ;
nC E E * 9 ;
nC f f * 9 ;
nC F F * 9 ;
nC g g * 9 ;
nC G G * 9 ;
nC h h * 9 ;
nC H H * 9 ;
nC i i * 9 ;
nC I I * 9 ;
nC j j * 9 ;
nC J J * 9 ;
nC k k * 9 ;
nC K K * 9 ;
nC l l * 9 ;
nC L L * 9 ;
nC m m * 9 ;
nC M M * 9 ;
nC n n * 9 ;
nC N N * 9 ;
nC o o * 9 ;
nC O O * 9 ;
nC p p * 9 ;
nC P P * 9 ;
nC q q * 9 ;
nC Q Q * 9 ;
nC r r * 9 ;
nC R R * 9 ;
nC s s * 9 ;
nC S S * 9 ;
nC t t * 9 ;
nC T T * 9 ;
nC u u * 9 ;
nC U U * 9 ;
nC v v * 9 ;
nC V V * 9 ;
nC w w * 9 ;
nC W W * 9 ;
nC x x * 9 ;
nC X X * 9 ;
nC y y * 9 ;
nC Y Y * 9 ;
nC z z * 9 ;
nC Z Z * 9 ;
nC ( ( * fC ;
fC ] ] l fC1 ;
fC * * l fC ;
fC1 _ [ * cl ;
fC1 * * l fC1 ;
cl [ _ r cl ;
cl ] _ r cl ;
cl ~ _ r cl ;
cl ( _ r clO ;
clO ) _ * halt-accept ;
clO * _ r clO ;
cl ) ) * halt-accept ;
cl * * r cl ;

Try it online!

Only handles alphanumerics at the moment. But can be extended rather trivially to handle any charactes of most UTF sets.

ouflak

Posted 2015-10-30T16:16:15.190

Reputation: 925

1

Plumber, 16 bytes

[]=[[]
 [[[[=
][][

First answer in my new esolang!

Programs in plumber are divided into 2 character wide units, each of which performs a certain function. All [] units on the top row will drop a packet containing the value 0. The one on the right will hit the [=, which will pop input and push it left into a right-facing branch dropper ([[). Branch droppers push in the direction they are facing, and also drop the value. When the value is pushed into the [=, it is outputted.

Plumber uses -1 for EOF, and outputting a negative value does nothing. When the value drops into the ][][, it moves upward on the far left, passes through an increment ([) operator, and is picked up by the []. If it is not 0, is passes through the conditional (=[), and is dropped by the [] on the right. This continues until the input is -1.

Redwolf Programs

Posted 2015-10-30T16:16:15.190

Reputation: 2 561

1

AppleScript, 50 Bytes

(display dialog""default answer"")'s text returned

Opens a display dialog (equivalent to STDIN) and returns all the text input into the dialog pane out to the result pane. Will not support infinite input.

Addison Crump

Posted 2015-10-30T16:16:15.190

Reputation: 10 763

1

osascript, 14 bytes

on run a
a
end

Grabs all input from STDIN and returns it. This will not work for infinite input.

Addison Crump

Posted 2015-10-30T16:16:15.190

Reputation: 10 763

This prints a trailing newline - I'm not sure how to get rid of it, but I'll try a few things. – Addison Crump – 2015-10-30T16:45:58.533

1

Ruby, 22 bytes

putc$_ while$_=$<.getc

Should handle null bytes and infinite streams.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1

Curry, 16 bytes

main=interact id

Curry is a Haskell look-alike, so it shouldn't be surprising that a cat program looks... well, exactly the same in it :) It's lazy just like Haskell, so it handles infinite streams fine.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1

Burlesque, 1 byte

Q

STDIN is pushed on the stack as a string. Q pretty-prints this string, which amounts to Burlesque not printing it "raw", i.e. surrounded by quotes. It's implicitly printed at the end of the program.

(I can't test it right now, but this might handle infinite streams? It's implemented in Haskell, so...)

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

It handles infinite streams as well, yes. You can work on infinite streams i.e. try cat /dev/urandom | base64 | blsq --stdin "2coQ" and it will work just fine. However, not all built-ins are lazy. For example trying to do 2couN wont work because \[ is not lazy. Mapping however will work i.e. 2co)<-Q works fine. Also doing 2cop^ nor 2co^p will work. – mroman – 2015-11-13T17:25:10.600

Additionally you need to know that some built-ins don't work natively on strings but Explode them and then Concat them back. That's why f[ won't work on infinite strings because f[ will do an auto-concat afterwards. So if you want to filter an infinite string you need to convert it to a block. For example XX:><2co)\[)rib2 works on infinite strings but if you don't do the XX it won't :). – mroman – 2015-11-13T17:30:14.050

I think the reason is that \[ falls back to r[ and r[ produces a single value out of a block and thus can't possibly work on infinite lists. – mroman – 2015-11-13T17:32:45.040

1

Frege, 16 bytes

main=interact id

Another Haskell-like, another totally equivalent cat program.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1

Pascal, 64 bytes

var c:Char;begin while not eof do begin read(c);write(c)end end.

Needless to say, Pascal is not the ideal golfing language.

kirbyfan64sos

Posted 2015-10-30T16:16:15.190

Reputation: 8 730

1

Oberon, 109 bytes

MODULE m;IMPORT Files,Out,In;VAR c:CHAR;BEGIN WHILE~Files.Eof(Files.stdin)DO In.Char(c);Out.Char(c)END END m.

Ouch...

kirbyfan64sos

Posted 2015-10-30T16:16:15.190

Reputation: 8 730

1

Java, 118 bytes

class A{public static void main(String[]a)throws Exception{org.apache.commons.io.IOUtils.copy(System.in,System.out);}}

(Uses apache commons IO; I'm not actually sure what the behavior is with null bytes and with infinite text).

Pokechu22

Posted 2015-10-30T16:16:15.190

Reputation: 213

1

Kipple, 5 Bytes

Calling the program:

java -jar Kipple.jar -i [input] cat.k

Stored in a file called cat.k - replace this with the filename.

Code:

(i>o)

As this is on the wiki page, I will be posting this as a community wiki.

Addison Crump

Posted 2015-10-30T16:16:15.190

Reputation: 10 763

1

Simplex v.0.7, 2 bytes

g is perhaps my favorite command. It is short for {sL}, {sp}, and Ts.

bg 
b  ~~ take input and write input to strip
 g ~~ output contents of strip

Conor O'Brien

Posted 2015-10-30T16:16:15.190

Reputation: 36 228

1

TI-Basic, 12 10 bytes

While 1
Input Str1
Disp Str1

DanTheMan

Posted 2015-10-30T16:16:15.190

Reputation: 3 140

Doesn't this need to loop and accept multiple lines/pieces of input? The rules aren't very clear in this case, but I think you do. – Shelvacu – 2015-10-30T20:25:01.923

@Shel I will get right to it then! – DanTheMan – 2015-10-30T20:30:02.657

1You can't take input from Ans; Input is the closest thing to STDIN. Strings also need to be supported; you can fix that by taking input into Str1 instead of A. – lirtosiast – 2015-10-31T17:47:18.537

1

Lua, 31 characters

::a::io.write(io.read(1))goto a

Will crash on EOF, as io.read(1) returns nil, which is an invalid argument to io.write. This needs Lua's goto statement, which is new since version 5.2.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

The default for io.read() is the file descriptor 1, you could save 1 Byte by writing ::a::io.write(io.read())goto a. – Katenkyo – 2016-03-02T15:29:54.447

1

C#, 83 bytes

using c=System.Console;class A{static void Main(){for(;;)c.Write((char)c.Read());}}

Seems to be shorter than using static, which another (faulty) answer here was using.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1It should terminate on end of stream, right? – Zereges – 2015-10-31T22:58:05.780

1

Visual Basic.NET, 87 bytes

Imports c=System.Console
Module A
Sub Main
c.Write(Chr(c.Read))
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.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1

F#, 74 bytes

type C=System.Console
[<EntryPoint>]let rec(!)x=C.Write(char(C.Read()));!x

Conceptually, this is similar to my C# and VB.NET answers. F# is strict about the type of main: it has to be precisely string[] -> int. The neat part is its name doesn't matter: whatever you mark as <EntryPoint> will be the program's main function. I saved a byte by calling it (!), a prefix operator, allowing me to write !x instead of m x or something.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1

Rust, 68 bytes

use std::io;fn main(){io::copy(&mut io::stdin(),&mut io::stdout());}

io::copy copies the entire contents of a reader into a writer. This function (I think) needs to borrow and mutate both stdin and stdout to do this, which is what &mut is about.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1

Julia, 35 bytes

while 0<1write(read(STDIN,Char))end

Similar to Alex's answer, but crashes at EOF. I think that's valid.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

Nevermind then. – Dennis – 2015-10-31T03:56:23.040

1Considering how similar it is to the other Julia answer, I probably would have left this as a comment instead. – Alex A. – 2015-10-31T05:57:12.470

I came up with almost this very answer (I had Int8 instead of Char, I'm not sure if mine would have worked for high bytes) before looking at yours -- but they were very similar when I compared them indeed! I think it's worth having both around though (a crashy one and a non-crashy one). – Lynn – 2015-10-31T10:51:02.590

1

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.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

You can save 1 byte by replacing 1_> with 1+ (n+1 is only 0 when n is -1). – 12Me21 – 2018-01-31T13:58:09.497

1

Pip, 1 + 2 = 3 bytes

One byte for the code plus two for the flags -rn:

g

The -r flag reads all of stdin, splits into lines, and assigns the list to g. The code then prints g, with -n adding newlines between the elements.

This works for null bytes, but it doesn't allow for infinite input, and it will always have a newline at the end whether the input ends with one or not. It's possible to write a version that can handle infinite streams as long as they contain newlines:

W##YqPy

(See revision history for explanation.)

The rules state, "If it is at all possible in your language to support an arbitrary infinite input stream, your program has to work correctly in this case." However, Pip cannot echo an infinite stream that doesn't contain newlines. So the 3-byte version, which can't handle any infinite streams, is still valid according to the rules (thanks to Dennis for pointing this out).

DLosc

Posted 2015-10-30T16:16:15.190

Reputation: 21 213

The longer version supports infinite lines of finite length, but not an arbitrary, infinite stream of bytes. For example, yes | tr -d \\n | ./pip.py cat.pip prints nothing before getting killed by the OOM manager. – Dennis – 2015-10-31T20:41:43.817

*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.* That means your 3 byte solution is valid, doesn't it? – Dennis – 2015-11-01T00:50:32.610

@Dennis You're right--edited. – DLosc – 2015-11-01T03:47:12.697

1

Nim, 53 bytes

while not stdin.endOfFile:stdout.write stdin.readChar

Not much to say here. I need sleep now. :)

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1

FlogScript, 1 byte

"

I lied. Here's one more, before anyone else gets to it. Doesn't handle infinite streams.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1

TECO, 4 bytes

<^T^T>

^T is CTRL+T. It should be self-explanatory how this works.

For those of you who can't read this infamously write-only language, it simply loops over the input (<>), reading (^T) and immediately printing (^T) bytes.

Mark

Posted 2015-10-30T16:16:15.190

Reputation: 2 099

1

Changeling, 0 bytes

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

Try it online!

Dennis

Posted 2015-10-30T16:16:15.190

Reputation: 196 637

1

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

Sp3000

Posted 2015-10-30T16:16:15.190

Reputation: 58 729

1

jq, 3 bytes

.

Invoke with two flags: jq -rR '.'.

jq is like sed for JSON. Each program is a filter on some input object, which is represented as . in the code, so jq '.' will echo input to output. -R tells jq to handle input as a stream of strings (lines) instead of JSON objects; -r tells it to do the same for output.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

Actually jq '' will also echo input to output. – manatwork – 2016-05-02T11:40:14.753

1

K (Kona), 6 bytes

`0:0:`

0: is a verb that reads/writes text files. Specifically, x 0: y writes y to the file x, and 0: y reads from the file y. However, if either of these file arguments is the empty symbol `, standard I/O will be used. This seems to be the only internal interface to stdin in the K language, i.e. not counting system calls like \cat.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1

Glass, 26 characters

{M[maI!ac.?aO!ao.?a$am.?]}

Glass is an object-oriented esoteric programming language! You don't see those often. It combines the joy of stack juggling and one-byte-per-instruction unreadability with the lesser joy of programming in Java.

In Java-ish pseudocode, this is something like

class Main {
  main {
    a = new I
    a.c()        // read a character, or die on EOF
    a = new O
    a.o()        // print it
    a = this
    a.main()     // loop
  }
}

The reference implementation crashes due to a stack overflow, but the spec doesn't specify a stack size, and there's no reason you couldn't optimize tail calls and make it work for any stream.

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1

Prelude, 5 bytes

?(!?)

This works essentially like the Brainfuck solution, except that the value is pushed onto/popped from a stack instead of written to/read from a tape.

Prelude cannot possibly handle null bytes, as EOF is signified as 0.

Martin Ender

Posted 2015-10-30T16:16:15.190

Reputation: 184 808

1

Ceylon (on JVM), 141 111 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() {
    while(exists l = process.readLine()){
        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);
    while (0 < i.read(a)) {
        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;
    while (0 <(r= i.read())) {
        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
// My answer: http://codegolf.stackexchange.com/a/62462/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. 
    while (0 < S.\iin.read(a)) {
        // 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);}}

Paŭlo Ebermann

Posted 2015-10-30T16:16:15.190

Reputation: 1 010

1

Cat, 31 bytes

[readch 1new_str write]-1repeat

A concatenative programming language inspired by Joy. It seems to be dead...

Something something right tool for the job.

(repeat is implemented as decrementing a repeat counter until it reaches zero. If you pass it -1, it'll count downwards from there and never reach zero, looping forever. This is shorter than a while loop.)

Lynn

Posted 2015-10-30T16:16:15.190

Reputation: 55 648

1

, 2 chars / 4 bytes

ôï

Try it here (Firefox only).

Mama Fun Roll

Posted 2015-10-30T16:16:15.190

Reputation: 7 234

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

  1. Removed i2c before invoking print (-4 bytes)
  2. Removed .limit stack 2 (-15 bytes)
  3. Extend PrintStream instead of Object to shorten invocation of print (-15 bytes)
  4. Return in the middle of the method instead of end. This makes on the the branch offsets shorter making the next change possible
  5. Make one of the branches a relative offset. This only saves a byte when the relatice offset is less than or equal to 9 (-1 byte)
  6. Store input byte on the stack instead of going through a local variable

ankh-morpork

Posted 2015-10-30T16:16:15.190

Reputation: 1 350

You could remove the return stuff because of -noverify iirc – famous1622 – 2019-12-10T20:52:01.300

@famous1622 I think I tried that while golfing. The program compiles and runs correctly until it reaches the end of the input and the JVM segfaults. Unfortunately an error message is sent to stdout and not stderr, so that invalidates it for this challenge. – ankh-morpork – 2019-12-10T21:17:18.580

1

X86_64, 37 bytes

Disassembly:

0000000000000000 <a>:
   0:   31 c0                   xor    %eax,%eax
   2:   31 ff                   xor    %edi,%edi
   4:   48 89 e6                mov    %rsp,%rsi
   7:   ba 01 00 00 00          mov    $0x1,%edx
   c:   0f 05                   syscall 
   e:   48 85 c0                test   %rax,%rax
  11:   74 0b                   je     1e <b>
  13:   b8 01 00 00 00          mov    $0x1,%eax
  18:   ff c7                   inc    %edi
  1a:   0f 05                   syscall 
  1c:   eb e2                   jmp    0 <a>

000000000000001e <b>:
  1e:   b8 3c 00 00 00          mov    $0x3c,%eax
  23:   0f 05                   syscall 

Source:

a:
xor eax, eax
xor edi, edi
mov rsi, rsp
mov edx, 1
syscall
test rax, rax
jz b
mov eax, 1
inc edi
syscall
jmp a
b:
mov eax, 60
syscall

hibbarnt

Posted 2015-10-30T16:16:15.190

Reputation: 11

Insted of mov edx,1, you should be able to do cdq;inc dl. Instead of mov eax,60, you could mov al,60 – ninjalj – 2015-11-02T20:26:05.450

1

DarkBASIC Classic/Pro, 16 bytes

DarkBASIC Pro is a language targeted primarily at game development, and it doesn't have stdin/out. Instead this snippet takes text input from the keyboard and draws it directly to the screen (the input command draws input characters to the screen as they are received, and stores them in the specified variable after return is pressed).

do
input a$
loop

BMac

Posted 2015-10-30T16:16:15.190

Reputation: 2 118

1

Gnu Forth, 56 bytes

Gnu Forth has immediate control structure words, usable outside word definitions:

[begin] pad pad 1 stdin read-file + tuck type 1- [until]

The [until] can be dropped, and Gforth kindly assumes it was there:

[begin] pad pad 1 stdin read-file + tuck type 1-

Of course, invoking external programs is shorter:

sh dd

ninjalj

Posted 2015-10-30T16:16:15.190

Reputation: 3 018

1

LiveScript, 25 bytes

while true
 alert prompt!

Zane Martin

Posted 2015-10-30T16:16:15.190

Reputation: 31

1

Japt, 1 byte

Japt (JavaScript shortened) is a language I published last night. Interpreter

N

Like TeaScript, all input is stored in a single variable (although here it's N). Also like TeaScript, output is implicit.

Side note: The first (up to) 6 items in the input are stored in variables U through Z. If we knew there was only one item in the input, this code would work just as well:

U

ETHproductions

Posted 2015-10-30T16:16:15.190

Reputation: 47 880

Is this the first ever Japt solution posted here? – Shaggy – 2017-08-16T11:26:10.507

@Shaggy Nope, I actually posted this one before I had even written the interpreter :P Then there's this one and this one, so this is the fourth Japt answer.

– ETHproductions – 2017-08-16T11:54:23.407

1

Acc!, 27 bytes

Also works in Acc!!.

Count q while 1 {
Write N
}

This code can handle null bytes, but will error when input runs out, as it is impossible to handle that case in Acc!

pppery

Posted 2015-10-30T16:16:15.190

Reputation: 3 987

1

DStack, 5 bytes

0kckt

Language created by my few days ago

DarkPhantom

Posted 2015-10-30T16:16:15.190

Reputation: 191

What does kc do when you hit EOF? – Martin Ender – 2015-11-13T07:14:02.423

@MartinBüttner At the moment, the language does not say what happens in that case, and my implementation not see if it tried to read EOF (which I have to fix). In the case of this cat program, the only way to stop it is sending the null character. – DarkPhantom – 2015-11-13T18:57:47.707

1

Fishing, Dock length 2, 9 bytes

v+CC
  IP

I takes an input and P prints it. Note that N can be substituted for P to produce a trailing newline.

Arcturus

Posted 2015-10-30T16:16:15.190

Reputation: 6 537

1You might want to note that Fishing is not capable of a) preserving linefeeds, b) determining EOF, c) reading arbitrary infinite streams, because it always reads lines (waiting for a linefeed character)... at least as far as the reference interpreter goes. Also I don't think it's fair to count this by the dock length. The byte count of this code is 9 bytes. – Martin Ender – 2015-11-13T07:06:30.267

1

Go, 66 bytes

package main
import("io"
."os")
func main(){io.Copy(Stdout,Stdin)}

Go has an io.Copy function which writes what reads; until EOF.

tomasz

Posted 2015-10-30T16:16:15.190

Reputation: 281

1

ResPlicate, 36 bytes

4 2 0 -1 4 2 4 2 4 2 4 2 4 2 1 0 0 0

This was one of the earliest examples I made after implementing this language, so I have simply copied it from the linked wiki article, which I largely wrote. As was mentioned there, this program does not halt on EOF, and will continue asking for input until the interpreter is killed by force.

ResPlicate in a nutshell

Programs in ResPlicate are all comprised of a list of integers, which are inserted into a queue in order. Each step, the first two integers are popped as x and y. Then a list of x integers is popped (and padded with zeros if the queue had fewer than x elements) and re-enqueued y times. This is quite sufficient to ensure Turing-completeness. Indeed, it is even Turing-complete in the limited case that y is not allowed to exceed 2.

This simple language is extended with I/O in the following way: If x is zero and y is positive, y is output as a character. If x is zero and y is negative, a character is read from input, y+1 is added to it, and the result is enqueued.

Ungolfed

4 2 [0 -1 4 2]                  Enqueue 0 -1 (read one character) followed by this command.
4 2 [4 2 4 2]                   Enqueue 4 2 followed by this command.
4 2 [1 0 0 0]                   Put two copies of 1 0 0 0 on the cue.
                                This sequence and the one preceding it can be considered
                                together to be a single command which appends
                                1 0 0 0 to itself.

After these commands, the queue looks like this:

0 -1 4 2 0 -1 4 2 4 2 4 2 4 2 4 2 1 0 0 0 1 0 0 0

In other words, the program has decompressed itself into a copy of itself with 0 -1 prepended and 1 0 0 0 appended, and since the program will eventually (and forever) return to this state, this could be considered the "real" cat program. The execution continues like so:

0 -1                            Get a character from stdin, append it to the queue.
4 2 [0 -1 4 2]
4 2 [4 2 4 2]
4 2 [1 0 0 0]                   As above.
1 0 [0]                         Pop and discard the zero.
0 (x)                           Print the inputted character x.

After which the program is once again in the state I said it would return to.

quintopia

Posted 2015-10-30T16:16:15.190

Reputation: 3 899

1

Aubergine, 9 bytes

=ii=oo=ib

Aubergine in a nutshell

Aubergine has four variables and four 2-argument instructions. The variables a and b can be indirected as A and B to point to locations in the program, which can be read and written just like data, making it inherently self-modifying. The other variables are o, which refers to input or output depending on whether it is the second or first argument of the assignment instruction, and i, which is the instruction pointer. The four instructions are assignment (=), addition (+), subtraction (-), and conditional jump (:). The only constant literal available is 1. All variables are initialized to zero.

Ungolfed:

=ii                      NOP placeholder, since instruction pointer moves after jumps
=oo                      Read a character from stdin, print it to stdout.
=ib                      Send the instruction pointer to value of b, which is 0 by default

This version runs forever and must be killed manually. To make it so that it exits upon receiving a null byte, we must add 3 bytes:

=ii=ao=oa:ba

quintopia

Posted 2015-10-30T16:16:15.190

Reputation: 3 899

1

Chaîne, 2 bytes

Because strings.

|i
|  ; perform next character as instruction
 i ; takes input to the stack
   ; implicit: output stack

Conor O'Brien

Posted 2015-10-30T16:16:15.190

Reputation: 36 228

1

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>

rafaelcastrocouto

Posted 2015-10-30T16:16:15.190

Reputation: 315

1

ROOP, 5 bytes

I
W
O

Never ends.

DarkPhantom

Posted 2015-10-30T16:16:15.190

Reputation: 191

1

WhoScript, 39 bytes

1pr;v;#0 1;-;i;>;e;<;t=;ti;o;tl;pw;pr;d

I think its best explained by watching the stack change over time.

psychic_paper read          @ [input]
time_vortex                 @ [input]
  # 0 1                     @ [input, 0, 1]
  -                         @ [input, -1.0]
  integer                   @ [input, -1]
  pop                       @ [input]
  duplicate                 @ [input, input]
  push                      @ [input, input, -1]
  TARDIS =                  @ [input, input==-1]
  TARDIS if                 @ [input]
    opening                 @ [-1] (it won't come this far otherwise)
  TARDIS landing            @ [input | -1]
  psychic_paper write       @ []
  psychic_paper read        @ [input]
paradox                     @ Phew!

The program will accept any input so long as you don't find a character whose ASCII code is -1. The program works best if input is provided from the command line, else it will just take one character at a time until you quit providing new ones.

MCS-Kaijin

Posted 2015-10-30T16:16:15.190

Reputation: 109

1

AnnieFlow, 2 bytes

11

The first 1 indicates that the program accepts input, and the second 1 indicates that there is one stack. The output stack has no changeable behavior, so that's the only information the program needs. Because the output stack is always the first stack and the input stack is always the last stack, they coincide in this case, so when the input stack is filled, it outputs the same to STDOUT instead of storing it. In any program, after the input stack is filled it is popped to start the program. However, popping from the output stack halts the program. Therefore the program halts immediately after outputting the input. This was not an intended feature, it just happened to work out the way it does because of how the programming language works.

Fricative Melon

Posted 2015-10-30T16:16:15.190

Reputation: 1 312

1

Y, 4 bytes

i:gF

Simple enough. This two-link program takes input characters and prints them out as you feed input. Input an empty string to terminate. Explanation:

i:g F 
i      take input (string)
 :     duplicate
  g    print one item
    F  conditional link: pop N, and if N is zero (falsey), i.e. empty string, continue.
       otherwise, move to beginning of current link

Conor O'Brien

Posted 2015-10-30T16:16:15.190

Reputation: 36 228

1

SPARC (V9) assembly, 64 bytes

This runs on NetBSD (I seem to be running version 6.1.5). Disassembly with objdump:

0000000000100078 <.text>:
  100078:   9c 23 a0 08     sub  %sp, 8, %sp
  10007c:   82 10 20 03     mov  3, %g1
  100080:   90 10 00 00     mov  %g0, %o0
  100084:   92 10 00 0e     mov  %sp, %o1
  100088:   94 10 20 01     mov  1, %o2
  10008c:   91 d0 20 00     ta  0
  100090:   02 ca 00 07     brz  %o0, 0x1000ac
  100094:   82 10 20 04     mov  4, %g1
  100098:   90 10 20 01     mov  1, %o0
  10009c:   92 10 00 0e     mov  %sp, %o1
  1000a0:   94 10 20 01     mov  1, %o2
  1000a4:   10 bf ff f6     b  0x10007c
  1000a8:   91 d0 20 00     ta  0
  1000ac:   9c 03 a0 08     add  %sp, 8, %sp
  1000b0:   82 10 20 01     mov  1, %g1
  1000b4:   91 d0 20 00     ta  0

Explanation (line-by-line):

First of all, the SPARC architecture has a ton of registers. You have access to 32 of them at a time, called %gX, %iX, %lX, and %oX for X in [0..7]. There are also %pc for the program counter and %sp for the stack pointer.

sub %sp, 8, %sp

The stack grows downward. I didn't want to include a .data section, so I'm using the stack as storage. This expands it by 8 bytes.

mov 3, %g1
mov %g0, %o0
mov %sp, %o1
mov 1, %o2

Getting ready to do a syscall. The ABI in use here requires the syscall number in %g1 and the arguments in %o0, %o1, etc. According to syscall.h, read is 3. Register %g0 is always 0, so these lines equate to read(0, sp, 1).

ta 0

Those familiar with x86 assembly might want int 0x80 to do the syscall. In SPARC, we use a user-mode trap, and in NetBSD specifically it is the first one. Thus, ta 0.

brz %o0, 0x1000ac

A conditional branch: jump to address 0x1000ac if %o0 contains zero. We sometimes have to be careful with instruction order though, because every time the program encounters a branch, the next instruction is executed as well. In this case it doesn't make a difference, but it will later.

mov 4, %g1
mov 1, %o0
mov %sp, %o1
mov 1, %o2

Just like with read before, except we're using write (4) and stdout (1).

b 0x10007c
ta 0

An unconditional branch. Remember that thing about branches being weird? This executes the ta 0 to call the write we just prepared, then jumps back to address 0x10007c (to prepare to read again).

add %sp, 8, %sp

The target of the first branch we saw, here we prepare to exit. Start by putting the stack pointer back where it was.

mov 1, %g1
ta 0

We know that %o0 contains zero, since that was the condition of the branch that got us here. We want to exit with that status, so we simply call exit (1).

Source:

.global _start
.section .text
_start:
sub %sp,8,%sp
1:
mov 3,%g1
mov %g0,%o0
mov %sp,%o1
mov 1,%o2
t 0
brz %o0,2f
mov 4,%g1
mov 1,%o0
mov %sp,%o1
mov 1,%o2
b 1b
t 0
2:
add %sp,8,%sp
mov 1,%g1
t 0

Fox

Posted 2015-10-30T16:16:15.190

Reputation: 341

1

Fuzzy Octo Guacamole, 3 bytes

(non-competing, FOG is newer than the challenge)

(^)

Looks emotish (that's totally a word).

The ^ gets input, the X pops it and prints it.

The ( and ) denote the start and end of an infinite loop.

4 byte solution with a for loop:

?[?^]

The [ and ] denote a for loop, and the ? increments the counter, so it never runs out.

Weird implicit outputs means it prints the outputs automatically.

Rɪᴋᴇʀ

Posted 2015-10-30T16:16:15.190

Reputation: 7 410

Cool!!!!!!!!!!! – Conor O'Brien – 2016-03-18T22:28:54.240

This is the infinite cat challenge. 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. – Dennis – 2016-03-19T04:57:26.817

1

Reng v.1.2, 4 bytes

is~o

This takes input, skips if not a negative one (i.e. no input found). When s find a regular character, it skips over the ~ and outputs the input with o. Otherwise, it meets the ~ and ends execution. Input is like "string1" "string2" ... "stringN". Try it here!

The following 13-byte program allows you to feed input more than once, but only yields correct output provided you feed it in at the right time.

>isvo
/$$>is!

Input "Meow":

meoowww

Conor O'Brien

Posted 2015-10-30T16:16:15.190

Reputation: 36 228

1

Jelly, 1 byte

¹

Simply the identity function.

Ven

Posted 2015-10-30T16:16:15.190

Reputation: 3 382

1

Lua, 30 Bytes

Heavily base upon Lynn's answer, but as it is not updated anymore, I'll feel free ot post this 30 bytes answer.

::a::io.write(io.read())goto a

Katenkyo

Posted 2015-10-30T16:16:15.190

Reputation: 2 857

1

Tellurium, 2 bytes

i^

Pretty simple, eh?

What it does is get input from the user using the i command, and stores it in the tape in the currently selected item (in the code above, it's 0, the default).

After that, it prints the currently selected item's value using the ^ command. (whatever the user input).

m654

Posted 2015-10-30T16:16:15.190

Reputation: 765

1

APL, 6 bytes

⎕←⍞
→1

This has worked in all APLs since the beginning of time.

wait for input
⎕← Output that
→1 go to line 1

Adám

Posted 2015-10-30T16:16:15.190

Reputation: 37 779

1

Javascript (browser), 16 15 bytes

alert(prompt())

OldBunny2800

Posted 2015-10-30T16:16:15.190

Reputation: 1 379

1I like the rules abuse here... :-) By the way, you can save a byte by dropping the semicolon - JavaScript has automatic semicolon insertion, with only a few exceptions. Also, you probably should specify state this is for browsers only, since Node.js doesn't have either of these, but it does support console IO. – Isiah Meadows – 2016-05-20T01:50:38.500

Done! Thanks for the edit btw – OldBunny2800 – 2016-05-20T01:52:16.477

1Welcome! <filler to make SE happy> – Isiah Meadows – 2016-05-20T01:53:48.797

1

Archway, 7 bytes

/.\
\,/

According to Esolangs, this is the only useful program that can be written in the original Archway language.

George Gibson

Posted 2015-10-30T16:16:15.190

Reputation: 2 369

1

Archway 2, 19 bytes

   \
// .
  , /
+/\

George Gibson

Posted 2015-10-30T16:16:15.190

Reputation: 2 369

1

Clojure, 18 bytes

(print(read-line))

This 30-bytes program runs forever:

(while true(print(read-line)))

user8397947

Posted 2015-10-30T16:16:15.190

Reputation: 1 242

1Wouldn't this only read and print a single line? I'm pretty sure Clojure would be able to deal with arbitrary finite and even infinite streams instead. – Martin Ender – 2016-06-04T20:52:19.787

Wouldn't this only read and print a single line? 24 days later, I worked around it. – user8397947 – 2016-06-29T01:11:08.123

@dorukayhan It ((while true) still (prints a (read-line)))! You need to support infinite input without newlines if you can. – Erik the Outgolfer – 2016-06-29T16:26:23.653

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Well, considering Clojure is Java in disguise, (read-line) uses System.in, which can theoretically take infinitely many bytes. – user8397947 – 2016-06-29T16:30:06.623

@dorukayhan Does it support input without newlines? – Erik the Outgolfer – 2016-06-29T16:33:04.623

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ It requires you to press Enter now and then, but omits newlines. Does that count? – user8397947 – 2016-06-29T16:45:21.520

@dorukayhan If you run (sh) echo No newlines!|clojure script, will it output No newlines!? – Erik the Outgolfer – 2016-06-29T16:50:25.407

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Huh? – user8397947 – 2016-06-29T16:52:06.603

@dorukayhan i.e. If you input indirectly with no newlines, will it work? – Erik the Outgolfer – 2016-06-29T16:53:11.107

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Um... probably. – user8397947 – 2016-06-29T16:59:03.123

1Badly overdue disclaimer: This might be the first Clojure program I wrote – user8397947 – 2016-06-29T16:59:12.813

@dorukayhan I think what Erik is trying to say is that this doesn't seem to print anything for an infinite input stream which doesn't contain linefeeds, since read-line won't return until it finds a linefeed, so you never start printing in that case. – Martin Ender – 2016-06-30T08:27:26.143

1

Wat, 6 + 1 = 7 bytes

åó#ÐÑÅ

(This code don't have any rapport with DNA)

Explanation:

åó#ÐÑÅ

å      Read a character
 ó     Duplicate the top of the stack
  #    Skip the next character
   Ð   End the program
    Ñ  If the top of the stack is 0, go backward (execute Ð and end the program), otherwise go forward
     Å Print the character on the top of the stack
       After, the IP wrap and the line is reexecuted

TuxCrafting

Posted 2015-10-30T16:16:15.190

Reputation: 4 547

Wat – Robert Fraser – 2016-10-06T17:22:48.437

1

Omam, 137 bytes

the screams all sound the same
though the truth may vary
don't listen to a word i say
the screams all sound the same
this ship will carry

Note that I haven't copied it. In fact, I added this code there today.

Erik the Outgolfer

Posted 2015-10-30T16:16:15.190

Reputation: 38 134

Well, this is a beautiful language. – user8397947 – 2016-06-29T01:06:17.190

@dorukayhan It's in fact BF, but with different commands. Note that this, technically, is 5 lines, i.e. 5 commands. BF golfing tips apply. – Erik the Outgolfer – 2016-06-29T07:45:09.070

1

Apps Script + Google Sheets, 29 bytes

Script

function Q(s){return s}

Sheet

=q(B1)

Cell B1 is the input.

weatherman115

Posted 2015-10-30T16:16:15.190

Reputation: 605

By convention A1 is the input cell for cell-based languages, and you should be able to reduce =q(b1) to =q(A1 where Google Sheets will autoformat in the terminating ) – Taylor Scott – 2017-09-05T16:09:01.797

1

C++ (109 Bytes)

Thanks to Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ for reducing 4 bytes.

#include <iostream>
#include <string>
using namespace std;main(){string A,W;while(cin>>A)W+=A;cout<<W<<endl;}

user54200

Posted 2015-10-30T16:16:15.190

Reputation:

Can't you remove it though? Also, if I'm correct, char*A is -2 string A. That way then, I think, you can remove #include <string>\n for -18, and use #include<iostream> for -1. Also, since you will use std:: 2-3 times, you can remove using namespace std;, and replace cin, cout (and possibly endl?) with std::cin, std::cout and possible std::endl. – Erik the Outgolfer – 2016-06-29T13:26:40.047

1

J, 14 bytes

stdout]stdin''

Reads the entire input from stdin until EOF is reached and store it as an array of characters. Then output all of it to stdout. This will work when saved as a script to be run using jconsole, where scripts are programs for interpreted languages.

miles

Posted 2015-10-30T16:16:15.190

Reputation: 15 654

1

Fith, 7 bytes

read \.

read gets input from STDIN. The language cannot handle infinite streams. \. prints the string on top of the stack without a trailing newline.

jqblz

Posted 2015-10-30T16:16:15.190

Reputation: 2 062

1Can't do read\.? – Erik the Outgolfer – 2016-06-29T13:28:47.990

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ No. Fith's identifier rules are very lax, so read\. would be counted as a single token. – jqblz – 2016-06-29T16:18:37.240

1And why can't you do read . then? – Erik the Outgolfer – 2016-06-29T16:24:58.363

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ That adds a newline at the end of the string. My understanding was that that shouldn't happen. – jqblz – 2016-06-29T16:27:35.740

Oh, okay then.. – Erik the Outgolfer – 2016-06-29T16:28:08.693

1

BruhScript, 22 bytes

Source:

↺₀1Λ₀⍈+⍰'
∇

Encoded version hexdump:

0000000: 0099 009a 003a 0087 009a 008f 0051 008e  .....:.......Q..
0000010: 0061 0000 0069                           .a...i

Explanation:

↺                While loop. Take two niladic functions as arguments.
 ₀1Λ             A function that always return 1
    ₀⍈+⍰'<LF>∇   `'<c>` is a shorthand for «<c>», so this code print (⍈) the input (⍰) + a newline ('<LF>), and return None (∇)

TuxCrafting

Posted 2015-10-30T16:16:15.190

Reputation: 4 547

1

Racket, 52 bytes

A classical approach.

(copy-port(current-input-port)(current-output-port))

In Racket, default settings are stored in parameters which are invoked to obtain their value (or invoked with an argument to set them). This mechanism is also used to access/set the default input and output ports.

Winny

Posted 2015-10-30T16:16:15.190

Reputation: 1 120

1

Clora, 1 byte

!

Explanation:

! use Input as Output value

OPSXCQ

Posted 2015-10-30T16:16:15.190

Reputation: 151

1

Python 3, 21 bytes

print(input(),end='')

Oliver Ni

Posted 2015-10-30T16:16:15.190

Reputation: 9 650

1This doesn't support multiple lines nor an infinite stream – Blue – 2016-09-27T18:17:33.843

1Also, why not use print(end=input())? :P – FlipTack – 2016-12-30T10:57:36.020

1

QBIC, 4 bytes

_??A

Unfortunately, QBasic (and by extension QBIC) doesn't handle input very well. Comma's are only allowed if quotes are used (which then get stripped from the output). Newlines are another no-go.

steenbergh

Posted 2015-10-30T16:16:15.190

Reputation: 7 772

1

Pyke, 2 bytes

zr

Try it here!

z  - read_line()
 r - if no error: goto_start()

Blue

Posted 2015-10-30T16:16:15.190

Reputation: 26 661

1

Jelly, 5 bytes

ƈȮøL¿

Try it online!

This one is valid, unlike the other 1-byte one, which is 100% invalid:

¹

(command-line arg, not STDIN)

Erik the Outgolfer

Posted 2015-10-30T16:16:15.190

Reputation: 38 134

Thanks to Dennis for implementing EOF detection for that. – Erik the Outgolfer – 2016-09-28T15:35:23.457

1

reticular, 2 bytes

ip

This exits with an error, but works fine. Try it online!

ip
i   take a line of input (no newline)
 p  print it with a newline after

Conor O'Brien

Posted 2015-10-30T16:16:15.190

Reputation: 36 228

1

ABCR, 4 bytes

5cQx

Explanation:

5      while(peek(B)){  //Queue B peeks default to 1, so this infinite-loops
 c        dequeue(c)  // Queue C dequeues default to an input character if C is empty
  Q       print(c)   /* Prints peek at the queue, and peeks on an empty queue C
                        default to the register value, which was set by `c` */
   x    }

Steven H.

Posted 2015-10-30T16:16:15.190

Reputation: 2 841

1

Emotinomicon, 16 bytes

⏫⏪⏬⏩

Explanation:

⏫⏪⏬⏩
⏫             Get input
             Reverse Stack
    ⏪  ⏩     Loop
      ⏬       Output one char

Roman Gräf

Posted 2015-10-30T16:16:15.190

Reputation: 2 915

There is alerady a shorter answer.

– Erik the Outgolfer – 2016-10-09T11:12:58.753

Yes but if input multiple chars in the input popup the output is reversed – Roman Gräf – 2016-10-19T08:57:21.683

1

Racket 35 bytes

(let l()(displayln(read-line))(l))

Ungolfed:

(define (f)
    (let loop()
      (displayln
       (read-line))
      (loop)))

To run:

(f)

rnso

Posted 2015-10-30T16:16:15.190

Reputation: 1 635

1

C#, 79 bytes

using x=System.Console;class P{static void Main(){x.Write(x.In.ReadToEnd());}}

Thanks Lynn for the hint about using alias vs using static.

Grax32

Posted 2015-10-30T16:16:15.190

Reputation: 1 282

1

FEU, 0 bytes


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

TuxCrafting

Posted 2015-10-30T16:16:15.190

Reputation: 4 547

1

pb, 20 bytes

^w[B!0]{t[B]vb[T]^>}

It will print an input prompt, but I can't do anything about it. This language has no way of supporting infinite input.

Erik the Outgolfer

Posted 2015-10-30T16:16:15.190

Reputation: 38 134

1

Lolo, 2 bytes

Lo

Not very interesting for a language only made up of Ls and Os.
It's basically printing whats in the stack. Since there is nothing, it gets the input.

user47018

Posted 2015-10-30T16:16:15.190

Reputation:

1

TCL, 28 bytes

puts -nonewline [read stdin]

Grax32

Posted 2015-10-30T16:16:15.190

Reputation: 1 282

1

Common Lisp (Lispworks), 50 bytes

(defun f()(let((x(read-char)))(format t"~A"x)(f)))

Usage:

    CL-USER 165 > (f)
    aabbccdd

    112233

    ddeeff

sadfaf

Posted 2015-10-30T16:16:15.190

Reputation: 101

0

GW-BASIC, 33 bytes

WHILE 1:INPUT "",X$:PRINT X$:WEND

Pretty simple:

  • WHILE 1 is an infinite loop
  • INPUT "",X$ reads a string with no prompt
  • PRINT X$ prints the string
  • WEND is the end of the while loop

Screenshot:

screenshot

MD XF

Posted 2015-10-30T16:16:15.190

Reputation: 11 605

0

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

MD XF

Posted 2015-10-30T16:16:15.190

Reputation: 11 605

0

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

MD XF

Posted 2015-10-30T16:16:15.190

Reputation: 11 605

0

shortC, 10 bytes

AW_=~G)P~_

Dennis' winning C answer in shortC. Try it online!

MD XF

Posted 2015-10-30T16:16:15.190

Reputation: 11 605

0

Pyt, 3 bytes

`ƥł

Try it online!

`...ł  loops while top of stack is not 0
ƥ      prints top element

FantaC

Posted 2015-10-30T16:16:15.190

Reputation: 1 425

0

Momema, 18 bytes

z1-9*0z00*-9z=+1*0

Try it online!

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

Esolanging Fruit

Posted 2015-10-30T16:16:15.190

Reputation: 13 542

0

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

MD XF

Posted 2015-10-30T16:16:15.190

Reputation: 11 605

0

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.

hakr14

Posted 2015-10-30T16:16:15.190

Reputation: 1 295

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. – MilkyWay90 – 2018-11-10T02:28:50.357

0

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.

Weijun Zhou

Posted 2015-10-30T16:16:15.190

Reputation: 3 396

0

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.

Khuldraeseth na'Barya

Posted 2015-10-30T16:16:15.190

Reputation: 2 608

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.

vasilescur

Posted 2015-10-30T16:16:15.190

Reputation: 341

0

Reality, 0 bytes



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

Muhammad Salman

Posted 2015-10-30T16:16:15.190

Reputation: 2 361

0

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

Windmill Cookies

Posted 2015-10-30T16:16:15.190

Reputation: 601

Hi. Go to your gitHub and take a look. I suggested something – Muhammad Salman – 2018-05-09T08:07:54.697

0

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.

Bubbler

Posted 2015-10-30T16:16:15.190

Reputation: 16 616

0

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.

Jo King

Posted 2015-10-30T16:16:15.190

Reputation: 38 234

6-byte version that exits with an error – Esolanging Fruit – 2018-08-12T07:40:11.960

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)". – Esolanging Fruit – 2018-08-12T07:43:06.967

0

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.

ObsequiousNewt

Posted 2015-10-30T16:16:15.190

Reputation: 836

Your program has to exit on EOF. – Dennis – 2018-08-11T01:37:46.507

I don't think that's meaningful here. – ObsequiousNewt – 2018-08-11T01:38:15.210

What do you mean? – Dennis – 2018-08-11T01:39:22.220

0

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.

mrFoobles

Posted 2015-10-30T16:16:15.190

Reputation: 41

0

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

FireCubez

Posted 2015-10-30T16:16:15.190

Reputation: 857

0

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.

Jo King

Posted 2015-10-30T16:16:15.190

Reputation: 38 234

0

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

MilkyWay90

Posted 2015-10-30T16:16:15.190

Reputation: 2 264

Is this just another Unary clone? It's kinda hard to golf ,[.,] – Jo King – 2018-10-30T02:12:01.693

whats Unary? Also, once you learn the programming language, it becomes easy to golf – MilkyWay90 – 2018-10-30T02:12:45.467

It's just brainfuck converted to binary converted to unary. Unary

– Jo King – 2018-10-30T02:20:37.940

Yikes, the programming language is remarkably similar. – MilkyWay90 – 2018-10-30T15:10:58.517

0

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.

Renzo

Posted 2015-10-30T16:16:15.190

Reputation: 2 260

0

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.

ais523

Posted 2015-10-30T16:16:15.190

Reputation: 11

0

!@#$%^&*()_+, 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

Conor O'Brien

Posted 2015-10-30T16:16:15.190

Reputation: 36 228

0

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.

Doorknob

Posted 2015-10-30T16:16:15.190

Reputation: 68 138

0

Tamsin, 12 bytes

main=any/''.

Try it online!

Esolanging Fruit

Posted 2015-10-30T16:16:15.190

Reputation: 13 542

0

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!

Benjamin Urquhart

Posted 2015-10-30T16:16:15.190

Reputation: 1 262

0

@, 6 bytes

¤ōč

Explanation

¤   Forever,
 ō  output the
  č character input

user85052

Posted 2015-10-30T16:16:15.190

Reputation:

0

05AB1E, 2 bytes

I?

Try it online!

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

facepalm42

Posted 2015-10-30T16:16:15.190

Reputation: 405

2Doesn't seem to work for multiple lines. Though for one line, the empty program does work – Jo King – 2019-08-24T14:13:36.413

@JoKing Thanks, I'll improve my this version. – facepalm42 – 2019-08-24T22:16:34.830

2Also, I don't see why zero-length programs aren't valid "full programs" (that rule means functions aren't allowed) – pppery – 2019-08-25T01:44:26.640

@pppery Oh, really. I thought they mean no 0 byte programs, since I don't see any 0b programs. – facepalm42 – 2019-08-25T02:50:07.387

The very old TeaScript answer is 0 bytes, and that's just the first one that I've noticed, so as long as it works a 0-byter is fine. In this case, it doesn't work, and neither does I? – Unrelated String – 2019-08-26T20:53:18.013

It seems like to construct a fully functional cat program in 05ab1e, you'd need to use a strange interaction between I and | to detect EOF. – Unrelated String – 2019-08-26T21:06:45.067

0

Starry, 10 8 bytes

` , + .'

Try it Online!

HighlyRadioactive

Posted 2015-10-30T16:16:15.190

Reputation: 1 585

0

W, 0 bytes

Indeed just a boring built-in.


Pretty obvious. Execute the program like this:

python W.py code.w ['your-string']

Remember to escape non-alphanumeric characters.

user85052

Posted 2015-10-30T16:16:15.190

Reputation:

Re-forking done. – None – 2019-12-17T11:02:36.047

0

Reflections, 61 53 bytes

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

Test it in the browser!

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

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

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

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

wastl

Posted 2015-10-30T16:16:15.190

Reputation: 3 089

0

Stax, 1 bytes

m

Run and debug it

Explaination

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

Nanajnaiojneg

Posted 2015-10-30T16:16:15.190

Reputation: 11

-1

Python 3, 14 bytes

print(input())

Try it online!

Basic.

Dion

Posted 2015-10-30T16:16:15.190

Reputation: 35

This doesn't handle newlines – Jo King – 2020-02-17T21:24:27.817