Copy stdin to stdout

Revision as of 16:15, 6 February 2022 by Thundergnat (talk | contribs) (→‎{{header|C sharp}}: Regularize header markup to recommended on category page)

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.

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

8086 Assembly

<lang asm>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</lang>

Action!

<lang Action!>PROC Main()

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

RETURN</lang>

Output:

Screenshot from Atari 8-bit computer

COPY STDIN TO STDOUT

Ada

<lang 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;</lang>

Aime

<lang aime>file f; data b; f.stdin; while (f.b_line(b) ^ -1) {

   o_(b, "\n");

}</lang>

ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.8.3.win32

<lang algol68>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</lang>

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. <lang AWK>awk "//"</lang>

BCPL

<lang bcpl>get "libhdr"

let start() be $( let c = rdch()

   if c = endstreamch then finish
   wrch(c)

$) repeat</lang>

Brainf***

<lang brainf***>,[.,]</lang>

C

<lang C>

  1. include <stdio.h>

int main(){

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

} </lang>

C#

Works with: .NET Framework version 4.0 or later

<lang csharp> using System;

class Program {

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

} </lang>

C++

<lang cpp>#include <iostream>

  1. include <iterator>

int main() {

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

}</lang>

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

int main() {

   std::cout << std::cin.rdbuf();

}</lang>

CLU

<lang 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</lang>

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.

<lang gwbasic>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</lang>

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

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

</lang>

Crystal

<lang ruby>STDIN.each_line do |line|

 puts line

end</lang>

D

<lang d>import std.stdio;

void main() {

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

}</lang>

Dart

<lang dart>import 'dart:io';

void main() {

 var line = stdin.readLineSync();
 stdout.write(line);

}</lang>

Delphi

→ See Pascal

Draco

<lang 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</lang>

F#

<lang fsharp> let copy()=let n,g=stdin,stdout

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

copy() </lang>

Factor

<lang factor>USING: io kernel ;

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

Forth

Works with: gforth version 0.7.3

<lang forth>stdin slurp-fid type bye</lang>

FreeBASIC

<lang freebasic>#define FIN 255 'eof is already a reserved word

  1. 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</lang>

Frink

The special string "-" indicates reading from stdin. <lang frink>print[read["-"]]</lang>

Go

<lang 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()
   }   

}</lang>

Groovy

<lang Groovy>class StdInToStdOut {

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

}</lang>

Haskell

<lang Haskell>main = interact id </lang>

Java

Copies until no more input. <lang java> 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);
           }
       }
   }

} </lang>

Output:

Output interleaved. Stdin and Stdout are same window.

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

jq

<lang jq>jq -Rr .</lang>

Julia

<lang Julia>while !eof(stdin)

   write(stdout, read(stdin, UInt8))

end</lang>

Kotlin

<lang scala>fun main() {

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

}</lang>

Latitude

<lang latitude>while { $stdin eof? not. } do {

 $stdout putln: $stdin readln.

}.</lang>

Lua

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

Mercury

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

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

Nim

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

OCaml

<lang ocaml>try

 while true do
   output_char stdout (input_char stdin)
 done

with End_of_file -> ()</lang>

Ol

<lang scheme> (bytestream->port (port->bytestream stdin) stdout) </lang>

Pascal

<lang 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.</lang>

Perl

<lang perl> perl -pe </lang>

Phix

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

PicoLisp

<lang PicoLisp>(in NIL (echo))</lang>

Prolog

<lang Prolog> %File: stdin_to_stdout.pl

- initialization(main).

main :- repeat, get_char(X), put_char(X), X == end_of_file, fail. </lang>

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

Python

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

R

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

Racket

<lang racket>#lang racket

(let loop ()

 (match (read-char)
   [(? eof-object?) (void)]
   [c (display c)
      (loop)]))</lang>

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.

<lang perl6>raku -pe'.lines'</lang>

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>

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. <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.*/
 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. */</lang>

Ring

<lang ring> ? "give input: " give str ? "output: " + str </lang>

Output:
give input:
Ring Programming Language
output: Ring Programming Language

Rust

<lang Rust>use std::io;

fn main() {

   io::copy(&mut io::stdin().lock(), &mut io::stdout().lock());

}</lang>

Scala

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

<lang Scala>object CopyStdinToStdout extends App {

 io.Source.fromInputStream(System.in).getLines().foreach(println)

}</lang>

If it's being run directly by scala, 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>

Scheme

<lang scheme> (do ((c (read-char) (read-char)))

   ((eof-object? c) 'done)
 (display c))

</lang>

sed

<lang sh> sed -e </lang>

Seed7

<lang seed7>$ include "seed7_05.s7i";

 include "fileutil.s7i";

const proc: main is func

 begin
   copyFile(IN, OUT);
 end func;</lang>

Smalltalk

Works with: Smalltalk/X

<lang smalltalk>"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:[]</lang>

Standard ML

<lang sml>fun copyLoop () =

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

val () = copyLoop ()</lang>

Symsyn

<lang Symsyn> Loop [] []

    go Loop

</lang>

Tcl

<lang tcl>package require Tcl 8.5

chan copy stdin stdout

  1. fcopy stdin stdout for older versions</lang>

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. <lang ecmascript>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</lang>

zkl

<lang zkl>zkl --eval "File.stdout.write(File.stdin.read())"</lang>