File input/output

From Rosetta Code
Revision as of 17:09, 21 January 2007 by 75.69.129.108 (talk) (→‎[[UNIX Shell]]: Added space so example appears as continuous code block)
Task
File input/output
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the job is to create a file called "output.txt", and place in it the contents of the file "input.txt".

Perl

Interpreter: Perl 5.8.8

#!/usr/bin/perl -w

open INPUT, "<input.txt";
open OUTPUT, ">output.txt";

while ( <INPUT> ) {
  print OUTPUT $_;
}

mIRC

Compiler: mIRC

 alias Write2FileAndReadIt {
 .write myfilename.txt Goodbye Mike!
 .echo -a Myfilename.txt contains: $read(myfilename.txt,1)
 }

Python

Interpreter: Python 2.4

In short form:

 open("output.txt", "w").writelines(open("input.txt"))

With proper closing and exception-handling:

inputFile = open("input.txt","r")
try:
  outputFile = open("output.txt", "w")
  try:
    outputFile.writelines(inputFile)
  finally:
    inputFile.close()
finally:
  outputFile.close()

TCL

Interpreter: tclsh, eTcl, wish, tixwish

set in [open "input.txt" r]
set out [open "output.txt" w]
puts -nonewline $out [read $in]
close $in
close $out

Other File I/O:

#open file for writing
set myfile [open "README.TXT" w]
#write something to the file
puts $myfile "This is line 1, so hello world...."
#close the file
close $myfile


#open file for reading
set myfile [open "README.TXT" r]
#read something from the file
gets $myfile mydata
#show what was read from the file
#should print "This is line1, so hello world...."
puts $mydata
#close the file
close $myfile

UNIX Shell

Interpreter: Bourne Shell Operating System: UNIX

#!/bin/sh

while read a; do
    echo "$a"
done <input.txt >output.txt