Copy stdin to stdout: Difference between revisions

From Rosetta Code
Content added Content deleted
(Applesoft BASIC)
m (syntax highlighting fixup automation)
Line 5: Line 5:
=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==


<lang asm>READ: equ 3Fh ; MS-DOS syscalls
<syntaxhighlight lang="asm">READ: equ 3Fh ; MS-DOS syscalls
WRITE: equ 40h
WRITE: equ 40h
BUFSZ: equ 4000h ; Buffer size
BUFSZ: equ 4000h ; Buffer size
Line 26: Line 26:
done: ret
done: ret
section .bss
section .bss
buffer: resb BUFSZ</lang>
buffer: resb BUFSZ</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Main()
<syntaxhighlight lang="action!">PROC Main()
CHAR c
CHAR c


Line 37: Line 37:
UNTIL c=27 ;repeat until Esc key is pressed
UNTIL c=27 ;repeat until Esc key is pressed
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Copy_stdin_to_stdout.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Copy_stdin_to_stdout.png Screenshot from Atari 8-bit computer]
Line 46: Line 46:
=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure Copy_Stdin_To_Stdout is
procedure Copy_Stdin_To_Stdout is
Line 56: Line 56:
Put (C);
Put (C);
end loop;
end loop;
end Copy_Stdin_To_Stdout;</lang>
end Copy_Stdin_To_Stdout;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>file f;
<syntaxhighlight lang="aime">file f;
data b;
data b;
f.stdin;
f.stdin;
while (f.b_line(b) ^ -1) {
while (f.b_line(b) ^ -1) {
o_(b, "\n");
o_(b, "\n");
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<lang algol68>BEGIN
<syntaxhighlight lang="algol68">BEGIN
BOOL at eof := FALSE;
BOOL at eof := FALSE;
# set the EOF handler for stand in to a procedure that sets "at eof" to true #
# set the EOF handler for stand in to a procedure that sets "at eof" to true #
Line 75: Line 75:
# copy stand in to stand out #
# copy stand in to stand out #
WHILE STRING line; read( ( line, newline ) ); NOT at eof DO write( ( line, newline ) ) OD
WHILE STRING line; read( ( line, newline ) ); NOT at eof DO write( ( line, newline ) ) OD
END</lang>
END</syntaxhighlight>


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<lang gwbasic>0 GET C$ : PRINT C$; : GOTO</lang>
<syntaxhighlight lang="gwbasic">0 GET C$ : PRINT C$; : GOTO</syntaxhighlight>
=={{header|AWK}}==
=={{header|AWK}}==
Using the awk interpreter, the following command uses the pattern // (which matches anything) with the default action (which is to print the current line) and so copy lines from stdin to stdut.
Using the awk interpreter, the following command uses the pattern // (which matches anything) with the default action (which is to print the current line) and so copy lines from stdin to stdut.
<lang AWK>awk "//"</lang>
<syntaxhighlight lang="awk">awk "//"</syntaxhighlight>


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


let start() be
let start() be
Line 90: Line 90:
if c = endstreamch then finish
if c = endstreamch then finish
wrch(c)
wrch(c)
$) repeat</lang>
$) repeat</syntaxhighlight>


=={{header|Brainf***}}==
=={{header|Brainf***}}==
<lang brainf***>,[.,]</lang>
<syntaxhighlight lang="brainf***">,[.,]</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdio.h>


Line 106: Line 106:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{works with|.NET Framework|4.0 or later}}
{{works with|.NET Framework|4.0 or later}}
<lang csharp>
<syntaxhighlight lang="csharp">
using System;
using System;


Line 120: Line 120:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <iterator>
#include <iterator>


Line 135: Line 135:
);
);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


Shorter and quicker alternative:
Shorter and quicker alternative:
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


int main() {
int main() {
std::cout << std::cin.rdbuf();
std::cout << std::cin.rdbuf();
}</lang>
}</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>start_up = proc ()
<syntaxhighlight lang="clu">start_up = proc ()
pi: stream := stream$primary_input()
pi: stream := stream$primary_input()
po: stream := stream$primary_output()
po: stream := stream$primary_output()
Line 154: Line 154:
return
return
end
end
end start_up</lang>
end start_up</syntaxhighlight>


=={{header|Commodore BASIC}}==
=={{header|Commodore BASIC}}==
Line 193: Line 193:
The following program opens channels to devices chosen by the user, then uses the GET# and PRINT# I/O statements instead of the standard GET and PRINT (for typical keyboard/screen interaction.) When keyboard and/or screen are chosen, BASIC ignores the extra filename and file type parameters normally used for other devices. Peripheral devices (tape, disk drive) use STATUS register to flag end of file, however the keyboard does not. When using the keyboard, the program terminates on a CTRL-Z.
The following program opens channels to devices chosen by the user, then uses the GET# and PRINT# I/O statements instead of the standard GET and PRINT (for typical keyboard/screen interaction.) When keyboard and/or screen are chosen, BASIC ignores the extra filename and file type parameters normally used for other devices. Peripheral devices (tape, disk drive) use STATUS register to flag end of file, however the keyboard does not. When using the keyboard, the program terminates on a CTRL-Z.


<lang gwbasic>10 print chr$(147);chr$(14);
<syntaxhighlight lang="gwbasic">10 print chr$(147);chr$(14);
11 print "0:Keyboard 1:Tape 2:RS-232 3:Screen"
11 print "0:Keyboard 1:Tape 2:RS-232 3:Screen"
12 print "4-7:printers/plotters"
12 print "4-7:printers/plotters"
Line 207: Line 207:
50 if (d1=0 and a$=chr$(26)) or (d1>0 and st>0) then close 5:close 2:end
50 if (d1=0 and a$=chr$(26)) or (d1>0 and st>0) then close 5:close 2:end
60 print#2,a$;
60 print#2,a$;
70 goto 40</lang>
70 goto 40</syntaxhighlight>


{{output}}
{{output}}
Line 264: Line 264:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>#|Loops while reading and collecting characters from STDIN until EOF (C-Z or C-D)
<syntaxhighlight lang="lisp">#|Loops while reading and collecting characters from STDIN until EOF (C-Z or C-D)
Then concatenates the characters into a string|#
Then concatenates the characters into a string|#
(format t
(format t
(concatenate 'string
(concatenate 'string
(loop for x = (read-char *query-io*) until (or (char= x #\Sub) (char= x #\Eot)) collecting x)))
(loop for x = (read-char *query-io*) until (or (char= x #\Sub) (char= x #\Eot)) collecting x)))
</syntaxhighlight>
</lang>


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang ruby>STDIN.each_line do |line|
<syntaxhighlight lang="ruby">STDIN.each_line do |line|
puts line
puts line
end</lang>
end</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main() {
void main() {
Line 283: Line 283:
writeln(line);
writeln(line);
}
}
}</lang>
}</syntaxhighlight>


=={{header|Dart}}==
=={{header|Dart}}==
<lang dart>import 'dart:io';
<syntaxhighlight lang="dart">import 'dart:io';


void main() {
void main() {
var line = stdin.readLineSync();
var line = stdin.readLineSync();
stdout.write(line);
stdout.write(line);
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 297: Line 297:


=={{header|Draco}}==
=={{header|Draco}}==
<lang draco>\util.g
<syntaxhighlight lang="draco">\util.g


proc nonrec main() void:
proc nonrec main() void:
Line 318: Line 318:
esac
esac
do od
do od
corp</lang>
corp</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
let copy()=let n,g=stdin,stdout
let copy()=let n,g=stdin,stdout
let rec fN()=match n.ReadLine() with "EOF"->g.Write "" |i->g.WriteLine i; fN()
let rec fN()=match n.ReadLine() with "EOF"->g.Write "" |i->g.WriteLine i; fN()
fN()
fN()
copy()
copy()
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: io kernel ;
<syntaxhighlight lang="factor">USING: io kernel ;


[ read1 dup ] [ write1 ] while drop</lang>
[ read1 dup ] [ write1 ] while drop</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
{{works with|gforth|0.7.3}}
<lang forth>stdin slurp-fid type bye</lang>
<syntaxhighlight lang="forth">stdin slurp-fid type bye</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>#define FIN 255 'eof is already a reserved word
<syntaxhighlight lang="freebasic">#define FIN 255 'eof is already a reserved word
#include "crt/stdio.bi" 'provides the C functions getchar and putchar
#include "crt/stdio.bi" 'provides the C functions getchar and putchar
dim as ubyte char
dim as ubyte char
Line 344: Line 344:
char = getchar()
char = getchar()
if char = FIN then exit do else putchar(char)
if char = FIN then exit do else putchar(char)
loop</lang>
loop</syntaxhighlight>


=={{header|Frink}}==
=={{header|Frink}}==
The special string "-" indicates reading from stdin.
The special string "-" indicates reading from stdin.
<lang frink>print[read["-"]]</lang>
<syntaxhighlight lang="frink">print[read["-"]]</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 370: Line 370:
w.Flush()
w.Flush()
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang Groovy>class StdInToStdOut {
<syntaxhighlight lang="groovy">class StdInToStdOut {
static void main(args) {
static void main(args) {
try (def reader = System.in.newReader()) {
try (def reader = System.in.newReader()) {
Line 382: Line 382:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang Haskell>main = interact id </lang>
<syntaxhighlight lang="haskell">main = interact id </syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Copies until no more input.
Copies until no more input.
<lang java>
<syntaxhighlight lang="java">
import java.util.Scanner;
import java.util.Scanner;


Line 404: Line 404:


}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
Output interleaved. Stdin and Stdout are same window.
Output interleaved. Stdin and Stdout are same window.
Line 417: Line 417:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
JavaScript in the browser does not have a stdin or stdout, but using Node.js we have:
JavaScript in the browser does not have a stdin or stdout, but using Node.js we have:
<lang JavaScript>process.stdin.resume();
<syntaxhighlight lang="javascript">process.stdin.resume();
process.stdin.pipe(process.stdout);</lang>
process.stdin.pipe(process.stdout);</syntaxhighlight>


<lang bash>node index.js < index.js</lang>
<syntaxhighlight lang="bash">node index.js < index.js</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 428: Line 428:


=={{header|jq}}==
=={{header|jq}}==
<lang jq>jq -Rr .</lang>
<syntaxhighlight lang="jq">jq -Rr .</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang Julia>while !eof(stdin)
<syntaxhighlight lang="julia">while !eof(stdin)
write(stdout, read(stdin, UInt8))
write(stdout, read(stdin, UInt8))
end</lang>
end</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>fun main() {
<syntaxhighlight lang="scala">fun main() {
var c: Int
var c: Int
do {
do {
Line 442: Line 442:
System.out.write(c)
System.out.write(c)
} while (c >= 0)
} while (c >= 0)
}</lang>
}</syntaxhighlight>


=={{header|Latitude}}==
=={{header|Latitude}}==
<lang latitude>while { $stdin eof? not. } do {
<syntaxhighlight lang="latitude">while { $stdin eof? not. } do {
$stdout putln: $stdin readln.
$stdout putln: $stdin readln.
}.</lang>
}.</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Line 453: Line 453:


=={{header|Mercury}}==
=={{header|Mercury}}==
<syntaxhighlight lang="mercury">
<lang Mercury>


:- module stdin_to_stdout.
:- module stdin_to_stdout.
Line 496: Line 496:


%-----------------------------------------------------------------------------%
%-----------------------------------------------------------------------------%
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==


<lang nim>stdout.write readAll(stdin)</lang>
<syntaxhighlight lang="nim">stdout.write readAll(stdin)</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>try
<syntaxhighlight lang="ocaml">try
while true do
while true do
output_char stdout (input_char stdin)
output_char stdout (input_char stdin)
done
done
with End_of_file -> ()</lang>
with End_of_file -> ()</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(bytestream->port (port->bytestream stdin) stdout)
(bytestream->port (port->bytestream stdin) stdout)
</syntaxhighlight>
</lang>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>program writeInput(input, output);
<syntaxhighlight lang="pascal">program writeInput(input, output);
var
var
buffer: char;
buffer: char;
Line 525: Line 525:
write(buffer); // shorthand for write(output, buffer)
write(buffer); // shorthand for write(output, buffer)
end;
end;
end.</lang>
end.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>
<syntaxhighlight lang="perl">
perl -pe ''
perl -pe ''
</syntaxhighlight>
</lang>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
Line 540: Line 540:
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(in NIL (echo))</lang>
<syntaxhighlight lang="picolisp">(in NIL (echo))</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">
<lang Prolog>
%File: stdin_to_stdout.pl
%File: stdin_to_stdout.pl
:- initialization(main).
:- initialization(main).
Line 555: Line 555:
X == end_of_file,
X == end_of_file,
fail.
fail.
</syntaxhighlight>
</lang>


Invocation at the command line (with Swi-prolog):
Invocation at the command line (with Swi-prolog):
<syntaxhighlight lang="sh">
<lang sh>
swipl stdin_to_stdout.pl
swipl stdin_to_stdout.pl
</syntaxhighlight>
</lang>


=={{header|Python}}==
=={{header|Python}}==
Line 569: Line 569:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(let loop ()
(let loop ()
Line 575: Line 575:
[(? eof-object?) (void)]
[(? eof-object?) (void)]
[c (display c)
[c (display c)
(loop)]))</lang>
(loop)]))</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
Line 581: Line 581:
When invoked at a command line: Slightly less magical than Perl / sed. The p flag means automatically print each line of output to STDOUT. The e flag means execute what follows inside quotes. ".lines" reads lines from the assigned pipe (file handle), STDIN by default.
When invoked at a command line: Slightly less magical than Perl / sed. The p flag means automatically print each line of output to STDOUT. The e flag means execute what follows inside quotes. ".lines" reads lines from the assigned pipe (file handle), STDIN by default.


<lang perl6>raku -pe'.lines'</lang>
<syntaxhighlight lang="raku" line>raku -pe'.lines'</syntaxhighlight>


When invoked from a file: Lines are auto-chomped, so need to re-add newlines (hence .say rather than .print)
When invoked from a file: Lines are auto-chomped, so need to re-add newlines (hence .say rather than .print)
<lang perl6>.say for lines</lang>
<syntaxhighlight lang="raku" line>.say for lines</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 592: Line 592:
normally the console. &nbsp; So for REXX, this task equates to copying data
normally the console. &nbsp; So for REXX, this task equates to copying data
from the console to itself.
from the console to itself.
<lang rexx>/*REXX pgm copies data from STDIN──►STDOUT (default input stream──►default output stream*/
<syntaxhighlight lang="rexx">/*REXX pgm copies data from STDIN──►STDOUT (default input stream──►default output stream*/


do while chars()\==0 /*repeat loop until no more characters.*/
do while chars()\==0 /*repeat loop until no more characters.*/
call charin , x /*read a char from the input stream. */
call charin , x /*read a char from the input stream. */
call charout , x /*write " " " " output " */
call charout , x /*write " " " " output " */
end /*while*/ /*stick a fork in it, we're all done. */</lang>
end /*while*/ /*stick a fork in it, we're all done. */</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
? "give input: " give str
? "give input: " give str
? "output: " + str
? "output: " + str
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 612: Line 612:


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>use std::io;
<syntaxhighlight lang="rust">use std::io;


fn main() {
fn main() {
io::copy(&mut io::stdin().lock(), &mut io::stdout().lock());
io::copy(&mut io::stdin().lock(), &mut io::stdout().lock());
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
Line 622: Line 622:
For Scala 2's compiler <code>scalac</code>, a containing object is required:
For Scala 2's compiler <code>scalac</code>, a containing object is required:


<lang Scala>object CopyStdinToStdout extends App {
<syntaxhighlight lang="scala">object CopyStdinToStdout extends App {
io.Source.fromInputStream(System.in).getLines().foreach(println)
io.Source.fromInputStream(System.in).getLines().foreach(println)
}</lang>
}</syntaxhighlight>


If it's being run directly by <code>scala</code>, it can be shortened to one line, and run directly in the shell:
If it's being run directly by <code>scala</code>, it can be shortened to one line, and run directly in the shell:


<lang bash>scala -e "io.Source.fromInputStream(System.in).getLines().foreach(println)"</lang>
<syntaxhighlight lang="bash">scala -e "io.Source.fromInputStream(System.in).getLines().foreach(println)"</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==


<lang scheme>
<syntaxhighlight lang="scheme">
(do ((c (read-char) (read-char)))
(do ((c (read-char) (read-char)))
((eof-object? c) 'done)
((eof-object? c) 'done)
(display c))
(display c))
</syntaxhighlight>
</lang>


=={{header|sed}}==
=={{header|sed}}==


<syntaxhighlight lang="sh">
<lang sh>
sed -e ''
sed -e ''
</syntaxhighlight>
</lang>


=={{header|Seed7}}==
=={{header|Seed7}}==


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "fileutil.s7i";
include "fileutil.s7i";


Line 652: Line 652:
begin
begin
copyFile(IN, OUT);
copyFile(IN, OUT);
end func;</lang>
end func;</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{Works with|Smalltalk/X}}
{{Works with|Smalltalk/X}}
<lang smalltalk>"using Stream class's bulk copy method:"
<syntaxhighlight lang="smalltalk">"using Stream class's bulk copy method:"
Stdin copyToEndInto:Stdout.
Stdin copyToEndInto:Stdout.


Line 668: Line 668:
[
[
[ Stdout nextPut:(Stdin next) ] loop.
[ Stdout nextPut:(Stdin next) ] loop.
] on: StreamError do:[]</lang>
] on: StreamError do:[]</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun copyLoop () =
<syntaxhighlight lang="sml">fun copyLoop () =
case TextIO.input TextIO.stdIn of
case TextIO.input TextIO.stdIn of
"" => ()
"" => ()
| tx => copyLoop (TextIO.output (TextIO.stdOut, tx))
| tx => copyLoop (TextIO.output (TextIO.stdOut, tx))


val () = copyLoop ()</lang>
val () = copyLoop ()</syntaxhighlight>


=={{header|Symsyn}}==
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
<lang Symsyn>
Loop [] []
Loop [] []
go Loop
go Loop
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5


chan copy stdin stdout
chan copy stdin stdout
# fcopy stdin stdout for older versions</lang>
# fcopy stdin stdout for older versions</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
VBScript can't get single chars from stdin, so we have to implement it line to line. Ctrl-Z+Enter stops.
VBScript can't get single chars from stdin, so we have to implement it line to line. Ctrl-Z+Enter stops.
<syntaxhighlight lang="vb">
<lang vb>
do
do
s=wscript.stdin.readline
s=wscript.stdin.readline
wscript.stdout.writeline s
wscript.stdout.writeline s
loop until asc(left(s,1))=26
loop until asc(left(s,1))=26
</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
Line 703: Line 703:


Bytes are read from stdin and written to stdout until the return key is pressed.
Bytes are read from stdin and written to stdout until the return key is pressed.
<lang ecmascript>import "io" for Stdin, Stdout
<syntaxhighlight lang="ecmascript">import "io" for Stdin, Stdout


Stdin.isRaw = true // prevents echoing to the terminal
Stdin.isRaw = true // prevents echoing to the terminal
Line 713: Line 713:
}
}
System.print()
System.print()
Stdin.isRaw = false</lang>
Stdin.isRaw = false</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
Line 719: Line 719:
stdout, which displays the character on the monitor. This program can
stdout, which displays the character on the monitor. This program can
list a file to the screen like this: stdio <file.txt
list a file to the screen like this: stdio <file.txt
<lang XPL0>int C;
<syntaxhighlight lang="xpl0">int C;
loop [C:= ChIn(1);
loop [C:= ChIn(1);
if C = $1A \EOF\ then quit;
if C = $1A \EOF\ then quit;
ChOut(0, C);
ChOut(0, C);
]</lang>
]</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>zkl --eval "File.stdout.write(File.stdin.read())"</lang>
<syntaxhighlight lang="zkl">zkl --eval "File.stdout.write(File.stdin.read())"</syntaxhighlight>

Revision as of 22:22, 26 August 2022

Task
Copy stdin to stdout
You are encouraged to solve this task according to the task description, using any language you may know.

Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.

8086 Assembly

READ:	equ	3Fh		; MS-DOS syscalls
WRITE:	equ	40h
BUFSZ:	equ	4000h		; Buffer size
	cpu	8086
	bits	16
	org	100h
section	.text
read:	mov	ah,READ		; Read into buffer
	xor	bx,bx		; From STDIN (file 0)
	mov	cx,BUFSZ
	mov	dx,buffer
	int	21h
	test	ax,ax		; Did we read anything?
	jz	done		; If not, stop
	xchg	ax,cx		; Write as many bytes as read
	mov	ah,WRITE
	inc	bx		; To STDOUT (file 1)
	int	21h
	jmp	read		; Go get more
done:	ret	
section	.bss
buffer:	resb	BUFSZ

Action!

PROC Main()
  CHAR c

  DO 
    c=GetD(7)
    Put(c)
  UNTIL c=27 ;repeat until Esc key is pressed
  OD
RETURN
Output:

Screenshot from Atari 8-bit computer

COPY STDIN TO STDOUT

Ada

with Ada.Text_IO;

procedure Copy_Stdin_To_Stdout is
   use Ada.Text_IO;
   C : Character;
begin
   while not End_Of_File loop
      Get_Immediate (C);
      Put (C);
   end loop;
end Copy_Stdin_To_Stdout;

Aime

file f;
data b;
f.stdin;
while (f.b_line(b) ^ -1) {
    o_(b, "\n");
}

ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.8.3.win32
BEGIN
    BOOL at eof := FALSE;
    # set the EOF handler for stand in to a procedure that sets "at eof" to true #
    # and returns true so processing can continue                                #                               
    on logical file end( stand in, ( REF FILE f )BOOL: at eof := TRUE );
    # copy stand in to stand out                                                 #
    WHILE STRING line; read( ( line, newline ) ); NOT at eof DO write( ( line, newline ) ) OD
END

Applesoft BASIC

0 GET C$ : PRINT C$; : GOTO

AWK

Using the awk interpreter, the following command uses the pattern // (which matches anything) with the default action (which is to print the current line) and so copy lines from stdin to stdut.

awk "//"

BCPL

get "libhdr"

let start() be
$(  let c = rdch()
    if c = endstreamch then finish
    wrch(c)
$) repeat

Brainf***

,[.,]

C

#include <stdio.h>

int main(){
  char c;
  while ( (c=getchar()) != EOF ){
    putchar(c);
  }
  return 0;
}

C#

Works with: .NET Framework version 4.0 or later
using System;

class Program
{
    static void Main(string[] args)
    {
        Console.OpenStandardInput().CopyTo(Console.OpenStandardOutput());
    }
}

C++

#include <iostream>
#include <iterator>

int main() {
    using namespace std;
    noskipws(cin);
    copy(
        istream_iterator<char>(cin),
        istream_iterator<char>(),
        ostream_iterator<char>(cout)
    );
    return 0;
}

Shorter and quicker alternative:

#include <iostream>

int main() {
    std::cout << std::cin.rdbuf();
}

CLU

start_up = proc ()
    pi: stream := stream$primary_input()
    po: stream := stream$primary_output()
    
    while true do
         stream$putc(po, stream$getc(pi))
    end except when end_of_file:
         return
    end
end start_up

Commodore BASIC

Commodore BASIC assigns device #0 (keyboard) as the standard input device, and device #3 (screen) as the standard output device. By opening channels for input and/or output, data can be sent to/from files, printers, and other peripheral devices. Although the keyboard and screen are the default input and output devices, they can be read from and written to using the same conventions as other devices, which is useful if a program wants to allow a user to direct output elsewhere (e.g. printing a hard copy of a report instead of displaying it on the screen)

Commodore Device Addresses
Number Device
0 Keyboard
1 Datassette Tape Drive
2 User Port (RS-232)
3 Text Screen
4 IEC Bus Printers
5
6 IEC Bus Plotters
7
8-30 Floppy/Hard Disk Drives

The following program opens channels to devices chosen by the user, then uses the GET# and PRINT# I/O statements instead of the standard GET and PRINT (for typical keyboard/screen interaction.) When keyboard and/or screen are chosen, BASIC ignores the extra filename and file type parameters normally used for other devices. Peripheral devices (tape, disk drive) use STATUS register to flag end of file, however the keyboard does not. When using the keyboard, the program terminates on a CTRL-Z.

10 print chr$(147);chr$(14);
11 print "0:Keyboard  1:Tape  2:RS-232  3:Screen"
12 print "4-7:printers/plotters"
13 print "8-11:Disk Drives":print
14 input "Input device";d1
15 if d1=1 or d1>=8 then input "Filename for INPUT";i$
16 input "Output device";d2
17 if d2=1 or d2>=8 then input "Filename for OUTPUT";o$
18 print:if d1=0 then print "Begin typing. Press CTRL-Z to end.":print
20 open 5,d1,5,"0:"+i$+",s,r"
30 open 2,d2,2,"@0:"+o$+",s,w"
40 get#5,a$
50 if (d1=0 and a$=chr$(26)) or (d1>0 and st>0) then close 5:close 2:end
60 print#2,a$;
70 goto 40
Output:

The output sample below demonstrates the following device input-output combinations:

  • Keyboard (0) to Screen (3)
  • Keyboard (0) to Disk File (8)
  • Disk File (8) to Screen (3)


0:Keyboard  1:Tape  2:RS-232  3:Screen  
4-7:printers/plotters                   
8-11:Disk Drives                        
                                        
Input device? 0                         
Output device? 3                        
                                        
Begin typing. Press CTRL-Z to end.      
                                        
Hello. This is so much fun on Rosetta Code!                                     
                                        
Goodbye!                                
                                        
ready.   
run

0:Keyboard  1:Tape  2:RS-232  3:Screen  
4-7:printers/plotters                   
8-11:Disk Drives                        
                                        
Input device? 0                         
Output device? 8                        
Filename for OUTPUT? rosetta.txt        
                                        
Begin typing. Press CTRL-Z to end.      

[No echo of text because output is directed to file.]
                                        
ready.                                  
run

0:Keyboard  1:Tape  2:RS-232  3:Screen  
4-7:printers/plotters                   
8-11:Disk Drives                        
                                        
Input device? 8                         
Filename for INPUT? rosetta.txt         
Output device? 3                        
                                        
These device numbers are unique to the Commodore line of 8-bit computers.       
                                        
ready.                   
█

Common Lisp

#|Loops while reading and collecting characters from STDIN until EOF (C-Z or C-D)
Then concatenates the characters into a string|#
(format t
  (concatenate 'string 
    (loop for x = (read-char *query-io*) until (or (char= x #\Sub) (char= x #\Eot)) collecting x)))

Crystal

STDIN.each_line do |line|
  puts line
end

D

import std.stdio;

void main() {
    foreach (line; stdin.byLine) {
        writeln(line);
    }
}

Dart

import 'dart:io';

void main() {
  var line = stdin.readLineSync();
  stdout.write(line);
}

Delphi

→ See Pascal

Draco

\util.g

proc nonrec main() void:
    char c;
    while
        /* I/O is line-oriented, so first read characters
         * from the current line while that is possible */
        while read(c) do write(c) od;
        case ioerror()
            /* Then once it fails, if the line is empty,
             * try to go to the next line. */
            incase CH_MISSING:
                readln();
                writeln();
                true
            /* If it failed for another reason (which will be
             * EOF here), stop. */
            default:
                false
        esac
    do od
corp

F#

let copy()=let n,g=stdin,stdout
           let rec fN()=match n.ReadLine() with "EOF"->g.Write "" |i->g.WriteLine i; fN()
           fN()
copy()

Factor

USING: io kernel ;

[ read1 dup ] [ write1 ] while drop

Forth

Works with: gforth version 0.7.3
stdin slurp-fid type bye

FreeBASIC

#define FIN 255  'eof is already a reserved word
#include "crt/stdio.bi"  'provides the C functions getchar and putchar
dim as ubyte char
do
    char = getchar()
    if char = FIN then exit do else putchar(char)
loop

Frink

The special string "-" indicates reading from stdin.

print[read["-"]]

Go

package main

import (
    "bufio"
    "io"
    "os"
)

func main() {
    r := bufio.NewReader(os.Stdin)
    w := bufio.NewWriter(os.Stdout)
    for {
        b, err := r.ReadByte()       
        if err == io.EOF {
            return
        }
        w.WriteByte(b)
        w.Flush()
    }   
}

Groovy

class StdInToStdOut {
    static void main(args) {
        try (def reader = System.in.newReader()) {
            def line
            while ((line = reader.readLine()) != null) {
                println line
            }
        }
    }
}

Haskell

main = interact id

Java

Copies until no more input.

import java.util.Scanner;

public class CopyStdinToStdout {

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in);) {
            String s;
            while ( (s = scanner.nextLine()).compareTo("") != 0 ) {
                System.out.println(s);
            }
        }
    }

}
Output:

Output interleaved. Stdin and Stdout are same window.

Line 1.
Line 1.
Line 2.
Line 2.

JavaScript

JavaScript in the browser does not have a stdin or stdout, but using Node.js we have:

process.stdin.resume();
process.stdin.pipe(process.stdout);
node index.js < index.js
Output:
process.stdin.resume();
process.stdin.pipe(process.stdout);

jq

jq -Rr .

Julia

while !eof(stdin)
    write(stdout, read(stdin, UInt8))
end

Kotlin

fun main() {
    var c: Int
    do {
        c = System.`in`.read()
        System.out.write(c)
    } while (c >= 0)
}

Latitude

while { $stdin eof? not. } do {
  $stdout putln: $stdin readln.
}.

Lua

lua -e 'for x in io.lines() do print(x) end'

Mercury

:- module stdin_to_stdout.
:- interface.

:- import_module io.

:- pred main(io::di, io::uo) is det.

%-----------------------------------------------------------------------------%
%-----------------------------------------------------------------------------%

:- implementation.

:- import_module char.
:- import_module list.
:- import_module string.

%-----------------------------------------------------------------------------%



main(!IO) :-
    io.read_line_as_string(Result, !IO),
    (
        Result = ok(Line),
        io.write_string(Line, !IO),
        main(!IO)
    ;
        Result = eof
    ;
        Result = error(Error),
        io.error_message(Error, Message),
        io.input_stream_name(StreamName, !IO),
        io.progname("stdin_to_stdout", ProgName, !IO),
        io.write_strings([
            ProgName, ": ",
            "error reading from `", StreamName, "': \n\t",
            Message, "\n"
        ], !IO)
    ).

%-----------------------------------------------------------------------------%

Nim

stdout.write readAll(stdin)

OCaml

try
  while true do
    output_char stdout (input_char stdin)
  done
with End_of_file -> ()

Ol

(bytestream->port (port->bytestream stdin) stdout)

Pascal

program writeInput(input, output);
var
	buffer: char;
begin
	while not EOF() do
	begin
		read(buffer); // shorthand for read(input, buffer)
		write(buffer); // shorthand for write(output, buffer)
	end;
end.

Perl

perl -pe ''

Phix

without js
while true do
    integer ch = wait_key()
    if ch=#1B then exit end if
    puts(1,ch)
end while

PicoLisp

(in NIL (echo))

Prolog

%File: stdin_to_stdout.pl
:- initialization(main).

main :- repeat,
	get_char(X),
	put_char(X),
	X == end_of_file,
	fail.

Invocation at the command line (with Swi-prolog):

swipl stdin_to_stdout.pl

Python

python -c 'import sys; sys.stdout.write(sys.stdin.read())'

R

Rscript -e 'cat(readLines(file("stdin")))'

Racket

#lang racket

(let loop ()
  (match (read-char)
    [(? eof-object?) (void)]
    [c (display c)
       (loop)]))

Raku

(formerly Perl 6) When invoked at a command line: Slightly less magical than Perl / sed. The p flag means automatically print each line of output to STDOUT. The e flag means execute what follows inside quotes. ".lines" reads lines from the assigned pipe (file handle), STDIN by default.

raku -pe'.lines'

When invoked from a file: Lines are auto-chomped, so need to re-add newlines (hence .say rather than .print)

.say for lines

REXX

In the REXX language,   the   STDIN   (default input stream)   is normally the console,   and the   STDOUT   (default output stream)   is normally the console.   So for REXX, this task equates to copying data from the console to itself.

/*REXX pgm copies data from STDIN──►STDOUT (default input stream──►default output stream*/

  do while chars()\==0                           /*repeat loop until no more characters.*/
  call charin  , x                               /*read  a char from the  input stream. */
  call charout , x                               /*write "   "    "   "   output   "    */
  end   /*while*/                                /*stick a fork in it,  we're all done. */

Ring

? "give input: " give str
? "output: " + str
Output:
give input:
Ring Programming Language
output: Ring Programming Language

Rust

use std::io;

fn main() {
    io::copy(&mut io::stdin().lock(), &mut io::stdout().lock());
}

Scala

For Scala 2's compiler scalac, a containing object is required:

object CopyStdinToStdout extends App {
  io.Source.fromInputStream(System.in).getLines().foreach(println)
}

If it's being run directly by scala, it can be shortened to one line, and run directly in the shell:

scala -e "io.Source.fromInputStream(System.in).getLines().foreach(println)"

Scheme

(do ((c (read-char) (read-char)))
    ((eof-object? c) 'done)
  (display c))

sed

sed -e ''

Seed7

$ include "seed7_05.s7i";
  include "fileutil.s7i";

const proc: main is func
  begin
    copyFile(IN, OUT);
  end func;

Smalltalk

Works with: Smalltalk/X
"using Stream class's bulk copy method:"
Stdin copyToEndInto:Stdout.

"line wise"
[Stdin atEnd] whileFalse:[ Stdout nextPutLine:(Stdin nextLine) ].

"character wise"
[Stdin atEnd] whileFalse:[ Stdout nextPut:(Stdin next) ].

"no EOF test, but handle EOF Exception"
[
    [ Stdout nextPut:(Stdin next) ] loop.
] on: StreamError do:[]

Standard ML

fun copyLoop () =
  case TextIO.input TextIO.stdIn of
    "" => ()
  | tx => copyLoop (TextIO.output (TextIO.stdOut, tx))

val () = copyLoop ()

Symsyn

Loop [] []
     go Loop

Tcl

package require Tcl 8.5

chan copy stdin stdout
# fcopy stdin stdout for older versions

VBScript

VBScript can't get single chars from stdin, so we have to implement it line to line. Ctrl-Z+Enter stops.

do
  s=wscript.stdin.readline
  wscript.stdout.writeline s 
loop until asc(left(s,1))=26

Wren

In the following script, stdin and stdout are both assumed to be connected to a terminal.

Bytes are read from stdin and written to stdout until the return key is pressed.

import "io" for Stdin, Stdout

Stdin.isRaw = true // prevents echoing to the terminal
while (true) {
    var byte = Stdin.readByte()         // read a byte from stdin
    if (byte == 13) break               // break when enter key pressed
    System.write(String.fromByte(byte)) // write the byte (in string form) to stdout
    Stdout.flush()                      // flush output
}
System.print()
Stdin.isRaw = false

XPL0

Device 1 is stdin without echoing a character to the screen. Device 0 (or 1) is stdout, which displays the character on the monitor. This program can list a file to the screen like this: stdio <file.txt

int C;
loop    [C:= ChIn(1);
        if C = $1A \EOF\ then quit;
        ChOut(0, C);
        ]

zkl

zkl --eval "File.stdout.write(File.stdin.read())"