File IO

From Rosetta Code

(Redirected from File I/O)
Jump to: navigation, search
Task
File IO
You are encouraged to solve this task according to the task description, using any language you may know.
File IO is part of Short Circuit's Console Program Basics selection.

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

Contents

[edit] Ada

If the file line size exceeds the size of the input string the output file will contain extra new-line characters.

with Ada.Text_IO; use Ada.Text_IO;
procedure File_IO is
Input, Output : File_Type;
Line : String (1 .. 10_000);
Last : Natural;
begin
Create (Output, Out_File, "output.txt");
Open (Input, In_File, "input.txt");
while not End_Of_File (Input) loop
Get_Line (Input, Line, Last);
Put_Line (Output, Line (1 .. Last));
end loop;
Close (Input);
Close (Output);
end File_IO;

Note that it is possible to use a version of Get_Line that returns the read line as one string of unspecified length:

while not End_Of_File (Input) loop
Put_Line (Output, Get_Line (Input));
end loop;

But it is not recommended, because it would make program vulnerable to storage error problems.

The following example reads and writes each file one character at a time. There is no new-line issue.

with Ada.Sequential_Io;
 
procedure File_Io is
package Char_Io is new Ada.Sequential_Io(Character);
use Char_Io;
Infile, Outfile : File_Type;
Value : Character;
begin
Create(File => Outfile, Mode => Out_File, Name => "output.txt");
Open(File => Infile, Mode => In_File, Name => "input.txt");
while not End_Of_File(Infile) loop
Read(File => Infile, Item => Value);
Write(File => Outfile, Item => Value);
end loop;
Close(Infile);
Close(Outfile);
end File_IO;

The following solution uses stream I/O. Any file of Ada.Text_IO can be used to obtain a corresponding stream. Reading and writing streams is more efficient than reading text files directly, because it skips formatting. Note also how End_Error exception is used to avoid End_Of_File. End_Of_File is depreciated as it requires file look-ahead, and thus is much less efficient.

with Ada.Text_IO;               use Ada.Text_IO; 
with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;
 
procedure File_Io is
Infile, Outfile : File_Type;
begin
Create (File => Outfile, Mode => Out_File, Name => "output.txt");
Open (File => Infile, Mode => In_File, Name => "input.txt");
loop
Character'Write (Stream (Outfile), Character'Input (Stream (Infile)));
end loop;
exception
when End_Error =>
Close (Infile);
Close (Outfile);
end File_IO;

[edit] ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used

Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

PROC copy file v1 = (STRING in name, out name)VOID: (
# note: algol68toc-1.18 - can compile, but not run v1 #
INT errno;
FILE in file, out file;
errno := open(in file, in name, stand in channel);
errno := open(out file, out name, stand out channel);
 
BOOL in ended := FALSE;
PROC call back ended = (REF FILE f) BOOL: in ended := TRUE;
on logical file end(in file, call back ended);
 
STRING line;
WHILE
get(in file, (line, new line));
# WHILE # NOT in ended DO # break to avoid excess new line #
put(out file, (line, new line))
OD;
ended:
close(in file);
close(out file)
);
 
PROC copy file v2 = (STRING in name, out name)VOID: (
INT errno;
FILE in file, out file;
errno := open(in file, in name, stand in channel);
errno := open(out file, out name, stand out channel);
 
PROC call back ended = (REF FILE f) BOOL: GO TO done;
on logical file end(in file, call back ended);
 
STRING line;
DO
get(in file, line);
put(out file, line);
get(in file, new line);
put(out file, new line)
OD;
done:
close(in file);
close(out file)
);
 
test:(
copy file v2("input.txt","output.txt")
)

[edit] AppleScript

on copyFile from src into dst
set filedata to read file src
set outfile to open for access dst with write permission
write filedata to outfile
close access outfile
end copyFile
 
copyFile from ":input.txt" into ":output.txt"

[edit] AutoHotkey

Method 1: the input file can be processed line by line.

Loop, Read, input.txt, output.txt
FileAppend, %A_LoopReadLine%`n

Method 2: the input file can be read at once if it is less than 1 GB.

FileRead, var, input.txt
FileAppend, %var%, output.txt

Method 3: the file can be copied without IO.

FileCopy, input.txt, output.txt

Binary IO is possible with this library from Laszlo.

[edit] AWK

(This does not handle properly binary files)

BEGIN {
while ( (getline <"input.txt") > 0 ) {
print >"output.txt"
}
}

[edit] Batch File

copy input.txt output.txt

or

type input.txt > output.txt

or

for /f "" %L in ('more^<input.txt') do echo %L>>output.txt

there may be other techniques too.

[edit] BASIC

Works with: QuickBasic version 4.5

 OPEN "INPUT.TXT" FOR INPUT AS #1
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
DO UNTIL EOF(1)
LINE INPUT #1, DATA$
PRINT #2, DATA$
LOOP
CLOSE #1
CLOSE #2
SYSTEM

[edit] Befunge

Works with: CCBI version 2.1

0110"txt.tupni"#@i10"txt.tuptuo"#@o@

This linear program tries to open "input.txt" as text file (or aborts). It then writes the content in text mode (i.e. minus trailing spaces) to "output.txt" (or aborts).

[edit] C

#include <stdio.h>
 
int main(int argc, char **argv) {
FILE *in, *out;
int c;
 
in = fopen("input.txt", "r");
if (!in) {
fprintf(stderr, "Error opening input.txt for reading.\n");
return 1;
}
 
out = fopen("output.txt", "w");
if (!out) {
fprintf(stderr, "Error opening output.txt for writing.\n");
fclose(in);
return 1;
}
 
while ((c = fgetc(in)) != EOF) {
fputc(c, out);
}
 
fclose(out);
fclose(in);
return 0;
}

A couple of remarks on the preceding example:

It uses fgetc to read one character at a time. Each character is visited, even though there's nothing to do with it. Copying bigger blocks of data is much more efficient.

It uses buffered IO to perform the move, which is overkill. This is not actually a weakness, but it invokes some overhead that you don't need.

The following example addresses those issues. To avoid buffered IO, it uses open(), read(), write() and close(), which are part of POSIX, but not defined of ANSI C.

Works with: POSIX

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
 
int main(int argc, char **argv)
{ int fi, fo;
int len;
char buf[1024]; /* a better choice is the FS block size, if you know it */
 
if ((fi = open("input.txt", O_RDONLY)) < 0) {
perror("Can't read input.txt");
return 1;
}
 
if ((fo = open("output.txt", O_WRONLY|O_CREAT|O_TRUNC)) < 0) {
perror("Can't write to output.txt");
return 1;
}
 
while ((len = read(fi, buf, 1024)) > 0) {
if (write(fo, buf, len) < 0) {
perror("write failed");
return 1;
}
}
 
if (len < 0) {
perror("read failed");
return 1;
}
 
close(fi); close(fo);
return 0;
}

[edit] C#

The long way:

using System.IO;
 
using (var reader = new StreamReader("input.txt"))
using (var writer = new StreamWriter("output.txt"))
{
var text = reader.ReadToEnd();
writer.Write(text);
}

The short way:

using System.IO;
 
var text = File.ReadAllText("input.txt");
File.WriteAllText("output.txt", text);

[edit] F#

open System.IO
 
let read = File.ReadAllText
let write file text = File.WriteAllText(file, text)
 
"input.txt" |> read |> write "output.txt"
 

[edit] C++

Works with: g++ version 3.4.2

#include <iostream>
#include <fstream>
#include <string>
 
using namespace std;
 
int main() {
string line;
ifstream input ( "input.txt" );
ofstream output ("output.txt");
 
if (output.is_open()) {
if (input.is_open()){
while (input) {
getline (input,line);
output << line << endl;
}
input.close(); // Not necessary - will be closed when variable goes out of scope.
}
else {
cout << "input.txt cannot be opened!\n";
}
output.close(); // Not necessary - will be closed when variable goes out of scope.
}
else {
cout << "output.txt cannot be written to!\n";
}
return 0;
}

Simpler version:

#include <iostream>
#include <fstream>
#include <cstdlib>
 
int main()
{
std::ifstream input("input.txt");
if (!input.is_open())
{
std::cerr << "could not open input.txt for reading.\n";
return EXIT_FAILURE;
}
 
std::ofstream output("output.txt");
if (!output.is_open())
{
std::cerr << "could not open output.txt for writing.\n";
return EXIT_FAILURE;
}
 
output << input.rdbuf();
if (!output)
{
std::cerr << "error copying the data.\n";
return EXIT_FAILURE;
}
 
return EXIT_SUCCESS;
}

Using istream- and ostream- iterators:

# include <algorithm>
# include <fstream>
 
int main() {
std::ifstream ifile("input.txt");
std::ofstream ofile("output.txt");
std::copy(std::istreambuf_iterator<char>(ifile),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(ofile));
}

Even simpler way:

#include <fstream>
 
int main()
{
std::ifstream input("input.txt");
std::ofstream output("output.txt");
output << input.rdbuf();
}

[edit] Clean

Define a function that copies the content from one file to another.

import StdEnv
 
copyFile fromPath toPath world
# (ok, fromFile, world) = fopen fromPath FReadData world
| not ok = abort ("Cannot open " +++ fromPath +++ " for reading")
# (ok, toFile, world) = fopen toPath FWriteData world
| not ok = abort ("Cannot open " +++ toPath +++ " for writing")
# (fromFile, toFile) = copyData 1024 fromFile toFile
# (ok, world) = fclose fromFile world
| not ok = abort ("Cannot close " +++ fromPath +++ " after reading")
# (ok, world) = fclose toFile world
| not ok = abort ("Cannot close " +++ toPath +++ " after writing")
= world
where
copyData bufferSize fromFile toFile
# (buffer, fromFile) = freads fromFile bufferSize
# toFile = fwrites buffer toFile
| size buffer < bufferSize = (fromFile, toFile) // we're done
= copyData bufferSize fromFile toFile // continue recursively

Apply this function to the world to copy a file.

Start world = copyFile "input.txt" "output.txt" world

[edit] Clojure

 
(use 'clojure.java.io)
 
(copy (file "input.txt") (file "output.txt"))
 

[edit] ColdFusion

<cfif fileExists(expandPath("input.txt"))>
<cffile action="read" file="#expandPath('input.txt')#" variable="inputContents">
<cffile action="write" file="#expandPath('output.txt')#" output="#inputContents#">
</cfif>

[edit] Common Lisp

By lines:

(with-open-file (in #p"input.txt" :direction :input)
(with-open-file (out #p"output.txt" :direction :output)
(loop for line = (read-line in nil 'foo)
until (eq line 'foo)
do (write-line line out))))

By arbitrary blocks and for possibly-binary files:

(defconstant +buffer-size+ (expt 2 16))
 
(with-open-file (in #p"input.txt" :direction :input
:element-type '(unsigned-byte 8))
(with-open-file (out #p"output.txt"
:direction :output
:element-type (stream-element-type in))
(loop with buffer = (make-array +buffer-size+
:element-type (stream-element-type in))
for size = (read-sequence buffer in)
while (plusp size)
do (write-sequence buffer out :end size))))

If you're on an odd platform which actually stores text/binary/... type information for files and your CL implementation will use this information, then in should be opened with :element-type :default.

[edit] D

Works with: D version 2

import std.file: copy;
 
void main() {
copy("input.txt", "output.txt");
}

Library: Tango Works with: D version 1

Copy the content from one file to another (exceptions are handled by Tango):

import tango.io.device.File;
 
void main()
{
auto from = new File("input.txt");
auto to = new File("output.txt", File.WriteCreate);
to.copy(from).close;
from.close;
}

Or a shorter example without explicitly closing the output file:

import tango.io.device.File;
 
void main()
{
auto to = new File("output.txt", File.WriteCreate);
to.copy(new File("input.txt")).close;
}

[edit] Delphi

Delphi supports both typed and untyped as well as a textfile type for files. Delphi provides a default 128 byte buffer for text files. This may be enlarged via a call to SetTextBuff(Var F: Text; Var Buf [Size : integer]) procedure. All other files have no buffer at all and it is the programmers option to do buffering.

The following file I/O procedures have existed since Turbo Pascal V-3.

- Read(F,V1..Vn)
- ReadLn(F,V1..Vn)
- Write(F,V1[,V2..Vn])
- WriteLn(f,V1[,V2..Vn])
- BlockRead(F,Buff,BytesToRead[,BytesRead])
- BlockWrite(F,Buff,BytesToRead[,BytesWritten])

Files are opened using:

AssignFile(f,{fully qualified path and file name})


Assigns the file name to the file structure in preparation for opening.

Reset(f)

Opens and existing file. If it does not exist EIOError is raised.


Rewrite(f)

Creates a new file and opens it for I/O. If the files exists is is overwritten.

Delphi implemented Streams of which a variant is TFileStream and are very closely related to the Windows API for file handling.

- Text File I/O -

var
f : TextFile ;
s : string ;
begin
AssignFile(f,[fully qualified file name);
Reset(f);
writeln(f,s);
Reset(f);
ReadLn(F,S);
CloseFile(
end;


- Untyped File I/O -

This is perhaps one of the most powerful I/O functions built into Pascal. This will allow you to open and read a file of ANY type, regardless of structure, size or content. Note the usage of Reset(). This is using the optional size parameter that instructs the record size of file I/O. This could have been called with SizeOf(Buff) as the optional parameter but that would have limited flexibility. Calling it with a size of ONE byte allows you to adjust the buffer size on the fly, as conditions warrant. Also note the use of the BytesRead parameter. When included in the BlockRead() function it will return the number of bytes actually read. If this is not included, then if your directive to read n bytes is greater then the size of the file, the EOF will be encountered unexpectedly and EIOError will be raised.

var
f : File ;
buff : array[1.1024] of byte ;
BytesRead : Integer ;
begin
AssignFile(f,fully qualified file name);
Reset(f,1);
Blockread(f,Buff,SizeOf(Buff),BytesRead);
CloseFile(f);
end;

- Typed File I/O -

Typed file I/O is very useful when reading and writing structures. An Address List is quiet easy to write when using this type of I/O. The same file procedures are used with some subtle differences. Bite below in the blockread and blockwrite procedures that the bytes to read or write are 1. Also note that the reset procedure is not called with a buffer size. When performing Typed File I/O the size of the type definition is the buffer size. In the BlockRead() and BlockWrite() procedures I elected to read one record. Had I declared a very large buffer of type tAddressBook of say 500 records, I could have set bytes to read as SizeOf(Buffer) thereby reading a minimum of 500 records.

type 
 
tAddressBook = Record
FName : string[20];
LName : string[30];
Address : string[30];
City : string[30];
State : string[2];
Zip5 : string[5];
Zip4 : string[4];
Phone : string[14];
Deleted : boolean ;
end;
 
var
f : file of tAddressBook ;
v : tAddressBook ;
bytes : integer ;
begin
AssignFile(f,fully qualified file name);
Reset(f);
Blockread(f,V,1,Bytes);
Edit(v);
Seek(F,FilePos(f)-1);
BlockWrite(f,v,1,bytes);
CloseFile(f);
end;

[edit] E

Works with: E-on-Java

<file:output.txt>.setText(<file:input.txt>.getText())

(This version holds the entire contents in memory.)

[edit] Factor

Holds entire file content in memory:

"input.txt" binary file-contents
"output.txt" binary set-file-contents

A bit longer, but only holds a small amount of data in memory. If opening the file for writing fails, we want to clean up the file that's open for reading:

[
"input.txt" binary <file-reader> &dispose
"output.txt" binary <file-writer> stream-copy
] with-destructors
 

Possibly cheating:

"input.txt" "output.txt" copy-file

[edit] Forth

Forth traditionally has not had any file handling capabilities, preferring instead to operate on a disk image block by block. Most modern Forth systems however run under an existing operating system and provide methods for disk access.

\ <to> <from> copy-file
: copy-file ( a1 n1 a2 n2 -- )
r/o open-file throw >r
w/o create-file throw r>
begin
pad maxstring 2 pick read-file throw
 ?dup while
pad swap 3 pick write-file throw
repeat
close-file throw
close-file throw ;
 
\ Invoke it like this:
s" output.txt" s" input.txt" copy-file

Note the use of "2 pick" to get the input file handle and "3 pick" to get the output file handle. Local or global variables could have been used, but in this implementation simple stack manipulation was chosen. Also, only maxstring bytes are copied at a time, and the global "pad" memory area is used to hold the data. For faster copies, allocating a larger buffer could be advantageous.

Also, abort" can be used instead of throw if desired.

[edit] Fortran

Works with: Fortran version 2003 Works with: gfortran version 4.3.2

It uses the access="stream" which is defined in Fortran 2003 standard and should allow to "copy" also binary data easily.

program FileIO
 
integer, parameter :: out = 123, in = 124
integer :: err
character(len=1) :: c
 
open(out, file="output.txt", status="new", action="write", access="stream", iostat=err)
if ( err == 0 ) then
open(in, file="input.txt", status="old", action="read", access="stream", iostat=err)
if ( err == 0 ) then
err = 0
do while ( err == 0 )
read(unit=in, iostat=err) c
if ( err == 0 ) write(out) c
end do
close(in)
end if
close(out)
end if
 
end program FileIO

[edit] Go

 
package main
 
import (
"io"
"log"
"os"
)
 
func CopyFile(out, in string) (err os.Error) {
var inf, outf *os.File
if inf, err = os.Open(in, os.O_RDONLY, 0666); err == nil {
defer inf.Close()
if outf, err = os.Open(out, os.O_WRONLY|os.O_CREATE, 0666); err == nil {
defer outf.Close()
_, err = io.Copy(outf, inf)
}
}
return
}
 
func main() {
if err := CopyFile("output.txt", "input.txt"); err != nil {
log.Exit(err)
}
}
 

[edit] Groovy

Using File

new File('output.txt').write(new File('input.txt').text)

Using Ant

new AntBuilder().copy(file:'input.txt', toFile:'output.txt', overwrite:true)

Buffered

new File('output.txt').withWriter( w ->
new File('input.txt').withReader( r -> w << r }
}

[edit] Haskell

Note: this doesn't keep the file in memory. Buffering is provided by lazy evaluation.

main = readFile "input.txt" >>= writeFile "output.txt"

[edit] HicEst

Copy via system call:

CHARACTER input='input.txt ', output='output.txt ', c, buffer*4096
SYSTEM(COPY=input//output, ERror=11) ! on error branch to label 11 (not shown)

Read and write line by line

OPEN(FIle=input, OLD, ERror=21) ! on error branch to label 21 (not shown)
OPEN(FIle=output)
DO i = 1, 1E300 ! "infinite" loop, exited on end-of-file error
READ( FIle=input, ERror=22) buffer ! on error (end of file) branch to label 22
WRITE(FIle=output, ERror=23) buffer ! on error branch to label 23 (not shown)
ENDDO
22 WRITE(FIle=output, CLoSe=1)

Read and write in 1 block

OPEN(FIle=input, SEQuential, UNFormatted, OLD, LENgth=len, ERror=31) ! on error branch to label 31 (not shown)
OPEN(FIle=output, SEQuential, UNFormatted, ERror=32) ! on error branch to label 32 (not shown)
ALLOCATE(c, len)
READ(FIle=input, CLoSe=1) c
WRITE(FIle=output, CLoSe=1) c END

[edit] IDL

; open two LUNs
openw,unit1,'output.txt,/get
openr,unit2,'
input.txt',/get
; how many bytes to read
fs = fstat(unit2)
; make buffer
buff = bytarr(fs.size)
; transfer content
readu,unit2,buff
writeu,unit1,buff
; that'
s all
close,/all

[edit] Icon and Unicon

Icon and Unicon I/O by default is line driven. This can be changed with options in open and by the use of reads() and writes().

[edit] Icon

procedure main()
in := open(f := "input.txt","r") | stop("Unable to open ",f)
out := open(f := "output.txt","w") | stop("Unable to open ",f)
while write(out,read(in))
end

[edit] Unicon

The Icon solution works in Unicon.

[edit] J

 'output.txt' (1!:2~ 1!:1)&< 'input.txt'

Or using the system library files:

require 'files'
'output.txt' (fwrite~ fread) 'input.txt'

[edit] Java

Works with: GCJ version 4.1.2

Simple version; Files may be closed automatically by OS, on some systems.

import java.io.*;
 
public class FileIODemo {
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("ouput.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}

This version closes both files after without OS intervention

import java.io.*;
 
public class FileIODemo2 {
public static void main(String args[]) {
try {
// Probably should wrap with a BufferedInputStream
final InputStream in = new FileInputStream("input.txt");
try {
// Probably should wrap with a BufferedOutputStream
final OutputStream out = new FileOutputStream("output.txt");
try {
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
out.close();
}
}
finally {
in.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}

Works with: Java version 1.4 Package nio

import java.io.*;
import java.nio.channels.*;
 
public class FileIODemo3 {
public static void main(String args[]) {
try {
final FileChannel in = new FileInputStream("input.txt").getChannel();
try {
final FileChannel out = new FileOutputStream("output.txt").getChannel();
try {
out.transferFrom(in, 0, in.size());
}
finally {
out.close();
}
}
finally {
in.close();
}
}
catch (Exception e) {
System.err.println("Exception while trying to copy: "+e);
e.printStackTrace(); // stack trace of place where it happened
}
}
}

This version is more in line with the other languages' implementations: it assumes simple text files, and doesn't worry too much about errors (just throws them out to the caller, the console in this case). It's shorter and simpler and shows that simple programs can be simple to write, in Java as well.

import java.io.*;
public class Test {
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
for (String line; (line = br.readLine()) != null; ) {
bw.write(line);
bw.newLine();
}
br.close();
bw.close();
}
}

[edit] JavaScript

Works with: JScript

var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2;
var f_in = fso.OpenTextFile('input.txt', ForReading);
var f_out = fso.OpenTextFile('output.txt', ForWriting, true);
 
// for small files:
// f_out.Write( f_in.ReadAll() );
 
while ( ! f_in.AtEndOfStream) {
// ReadLine() does not include the newline char
f_out.WriteLine( f_in.ReadLine() );
}
 
f_in.Close();
f_out.Close();

[edit] Liberty BASIC

nomainwin
 
open "input.txt" for input as #f1
qtyBytes = lof( #f1)
source$ = input$( #f1, qtyBytes)
close #f1
 
open "output.txt" for output as #f2
#f2 source$;
close #f2
 
end

[edit] Lisaac

Section Header
 
+ name := FILE_IO;
 
Section Public
 
- main <- (
+ e : ENTRY;
+ f : STD_FILE;
+ s : STRING;
 
e := FILE_SYSTEM.get "input.txt";
(e != NULL).if {
f ?= e.open_read_only;
(f != NULL).if {
s := STRING.create(f.size);
f.read s size (f.size);
f.close;
};
};
 
(s != NULL).if {
e := FILE_SYSTEM.make_file "output.txt";
(e != NULL).if {
f ?= e.open;
(f != NULL).if {
f.write s from (s.lower) size (s.count);
f.close;
};
};
};
);

[edit] Logo

Works with: UCB Logo

to copy :from :to 
openread :from
openwrite :to
setread :from
setwrite :to
until [eof?] [print readrawline]
closeall
end
 
copy "input.txt "output.txt

[edit] Lua

io.open("output.txt", "w"):write(io.open("input.txt", "r"):read("*a"))

[edit] MAXScript

inFile = openFile "input.txt"
outFile = createFile "output.txt"
while not EOF inFile do
(
format "%" (readLine inFile) to:outFile
)
close inFile
close outFile

[edit] Mathematica

SetDirectory@NotebookDirectory[];
If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ];
CopyFile["input.txt", "output.txt"]

[edit] mIRC Scripting Language

Works with: mIRC

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

[edit] Objective-C

Works with: Cocoa

Works with: GNUstep

Read the contents of input.txt and place it in output.txt, creating a file if needed:

NSData *data = [NSData dataWithContentsOfFile:@"input.txt"];
 
[data writeToFile:@"output.txt" atomically:YES];

Displayed without error checking to make it more clear. In real code you will need to add lot of error checking code, and maybe use dataWithContentsOfFile:error: if you want to get error information on failure. However, this code will mostly work correctly even if input does not exist or is not accessible. dataWithContentsOfFile: will return nil, and sending nil the message writeTofile:atomically: does nothing :-)

The second argument (atomically:YES) write the content to a temporary file, and rename the temporary file to the destination file, replacing existing file.

[edit] OCaml

By line:

let () =
let ic = open_in "input.txt" in
let oc = open_out "output.txt" in
try
while true do
let s = input_line ic in
output_string oc s;
output_char oc '\n';
done
with End_of_file ->
close_in ic;
close_out oc;
;;

By character:

let () =
let ic = open_in "input.txt" in
let oc = open_out "output.txt" in
try
while true do
let c = input_char ic in
output_char oc c
done
with End_of_file ->
close_in ic;
close_out oc;
;;

(Notice that ic and oc, of type in_channel and out_channel, are buffered)

[edit] Oz

declare
class TextFile from Open.file Open.text end
 
In = {New TextFile init(name:"input.txt")}
Out = {New TextFile init(name:"output.txt" flags:[write text create truncate])}
 
proc {CopyAll In Out}
case {In getS($)} of false then skip
[] Line then
{Out putS(Line)}
{CopyAll In Out}
end
end
in
{CopyAll In Out}
{Out close}
{In close}

[edit] Perl

Works with: Perl version 5.8.8

#!/usr/bin/perl
 
open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!";
open my $fh_out, '>', 'output.txt' or die "could not open <output.txt> for writing: $!";
# '>' overwrites file, '>>' appends to file, just like in the shell
 
binmode $fh_out; # marks filehandle for binary content on systems where that matters
 
print $fh_out $_ while <$fh_in>;
# prints current line to file associated with $fh_out filehandle
 
# the same, less concise
#while (<$fh_in>) {
# print $fh_out $_;
#};
 
close $fh_in;
close $fh_out;

Perl has also a powerful mechanism in conjunction with opening files called IO disciplines. It allows you to automatically apply chainable transformations on the input and output. Mangling newlines, gzip (de)compression and character encoding are the most used examples.

[edit] Perl 6

my $in = open "input.txt";
my $out = open "output.txt", :w;
for $in.lines -> $line {
$out.say($line);
}

or, using the new slurp operator:

(open "output.txt", :w).print(slurp "input.txt")

[edit] PHP

Works with: PHP version 4

<?php
 
if (!$in = fopen('input.txt', 'r')) {
die('Could not open input file.');
}
 
if (!$out = fopen('output.txt', 'w')) {
die('Could not open output file.');
}
 
while (!feof($in)) {
$data = fread($in, 512);
fwrite($out, $data);
}
 
fclose($out);
fclose($in);
?>

Works with: PHP version 5

<?php
if ($contents = file_get_contents('input.txt')) {
if (!file_put_contents('output.txt', $contents)) {
echo('Could not write output file.');
}
} else {
echo('Could not open input file.');
}
?>

[edit] PicoLisp

(in "input.txt"
(out "output.txt"
(echo) ) )

[edit] PL/I

 
declare in file, out file;
 
open file (in) title ('/INPUT.TXT,type(text),recsize(100)') input;
open file (out) title ('/OUTPUT.TXT,type(text),recsize(100) output;
do forever;
get file (in) edit (line) (L);
put file (out) edit (line) (A);
end;
 

[edit] Pop11

Char by char copy:

lvars i_stream = discin('input.txt');
lvars o_stream = discout('output.txt');
lvars c;
while (i_stream() ->> c) /= termin do
o_stream(c);
endwhile;

Low level block copy:

lvars i_file = sysopen('input.txt', 0, true);
lvars o_file = syscreate('output.txt', 1, true);
lvars buff = inits(4096);
lvars i;
while (sysread(i_file, buff, length(buff)) ->> i) > 0 do
syswrite(o_file, buff, i);
endwhile;

[edit] PowerShell

Read the input file then pipe it's contents to output file. Assumes that the files are in the same folder that the script is executing in.

Get-Content $PWD\input.txt | Out-File $PWD\output.txt

Using an alternate cmdlet to write the file

Get-Content $PWD\input.txt | Set-Content $PWD\output.txt

[edit] PureBasic

Basic file copy

CopyFile("input.txt","output.txt")


Line by line

in = ReadFile(#PB_Any,"input.txt")
If in
out = CreateFile(#PB_Any,"output.txt")
If out
Define MyLine$
While Not Eof(in)
MyLine$ = ReadString(in)
WriteString(out,MyLine$)
Wend
CloseFile(out)
EndIf
CloseFile(in)
EndIf


Reading & writing the complete file in one pass

If ReadFile(0,"input.txt")
Define MyLine$, *Buffer, length
length=FileSize("input.txt")
*Buffer = AllocateMemory(length)
If *Buffer
If OpenFile(1,"output.txt")
ReadData(0, *Buffer, length)
WriteData(1, *Buffer, length)
CloseFile(1)
EndIf
FreeMemory(*Buffer)
EndIf
CloseFile(0)
EndIf

[edit] Python

The following use of the standard libraries shutil.copyfile is to be preferred. (Current source code ensures that failure to open files raises appropriate exceptions, a restricted buffer is used to copy the files using binary mode, and any used file descriptors are always closed).

import shutil
shutil.copyfile('input.txt', 'output.txt')

However the following example shows how one would do file I/O of other sorts:

infile = open('input.txt', 'r')
outfile = open('output.txt', 'w')
for line in infile:
outfile.write(line)
outfile.close()
infile.close()

This does no error checking. A more robust program would wrap each open with exception handling blocks:

import sys
try:
infile = open('input.txt', 'r')
except IOError:
print >> sys.stderr, "Unable to open input.txt for input"
sys.exit(1)
try:
outfile = open('output.txt', 'w')
except IOError:
print >> sys.stderr, "Unable to open output.txt for output"
sys.exit(1)
try: # for finally
try: # for I/O
for line in infile:
outfile.write(line)
except IOError, e:
print >> sys.stderr, "Some I/O Error occurred (reading from input.txt or writing to output.txt)"
finally:
infile.close()
outfile.close()

In Python 2.6 (or 2.5 if we use from __future__ import with_statement) we can more simply write:

import sys
try:
with open('input.txt') as infile:
with open('output.txt', 'w') as outfile:
for line in infile:
outfile.write(line)
except IOError:
print >> sys.stderr, "Some I/O Error occurred"
sys.exit(1)

The files will automatically be closed on exit of their with: blocks. (Thus even if an I/O error occurred while reading the middle of the input file we are assured that the .close() method will have been called on each of the two files.

[edit] R

If files are textual we can use readLines ("-1" means "read until the end")

src <- file("input.txt", "r")
dest <- file("output.txt", "w")
 
fc <- readLines(src, -1)
writeLines(fc, dest)
close(src); close(dest)

If the files are not textual but "generic":

src <- file("input.txt", "rb")
dest <- file("output.txt", "wb")
 
while( length(v <- readBin(src, "raw")) > 0 ) {
writeBin(v, dest)
}
close(src); close(dest)

Another simpler way is to use file.copy

file.copy("input.txt", "output.txt", overwrite = FALSE)

[edit] REBOL

write %output.txt read %input.txt
 
; No line translations:
write/binary %output.txt read/binary %input.txt
 
; Save a web page:
write/binary %output.html read http://rosettacode.org
 

[edit] RapidQ

File I/O is one of the things where RapidQ differs from standard Basic. RapidQ uses file streams.

The first version copies text line by line, as in the BASIC example.

$INCLUDE "rapidq.inc"
 
DIM File1 AS QFileStream
DIM File2 AS QFileStream
 
File1.Open("input.txt", fmOpenRead)
File2.Open("output.txt", fmCreate)
 
WHILE NOT File1.EOF
data$ = File1.ReadLine
File2.WriteLine(data$)
WEND
 
File1.Close
File2.Close

When just copying data, the code can be simplified by using the CopyFrom method.
(The second parameter for CopyFrom is number of bytes to copy, 0 = copy the whole file.)

$INCLUDE "rapidq.inc"
 
DIM File1 AS QFileStream
DIM File2 AS QFileStream
 
File1.Open("input.txt", fmOpenRead)
File2.Open("output.txt", fmCreate)
 
File2.CopyFrom(File1, 0)
 
File1.Close
File2.Close

[edit] Raven

'input.txt' read 'output.txt' write

[edit] Ruby

Works with: Ruby version 1.8.4

 
File.open('output.txt', 'w') do |file|
file.write File.read 'input.txt'
end
 

OR

 
File.open('output.txt', 'w') { |file| file.write File.read 'input.txt' }
 

[edit] Slate

(File newNamed: 'input.txt' &mode: File Read) sessionDo: [| :in |
(File newNamed: 'output.txt' &mode: File CreateWrite) sessionDo: [| :out |
in >> out]]

[edit] Smalltalk

| in out |
in := FileStream open: 'input.txt' mode: FileStream read.
out := FileStream open: 'output.txt' mode: FileStream write.
[ in atEnd ]
whileFalse: [
out nextPut: (in next)
]

[edit] SNOBOL4

 
input(.input,5,,'input.txt')
output(.output,6,,'output.txt')
while output = input  :s(while)
end


[edit] Standard ML

Works with: SML/NJ version 110.59

fun copyFile (from, to) =
let
val instream = TextIO.openIn from
val outstream = TextIO.openOut to
val () = TextIO.output (outstream, TextIO.inputAll instream)
val () = TextIO.closeIn instream
val () = TextIO.closeOut outstream
in
true
end handle _ => false;

[edit] Tcl

Works with: tclsh

Works with: eTcl

Works with: wish

Works with: tixwish

set in [open "input.txt" r]
set out [open "output.txt" w]
# Obviously, arbitrary transformations could be added to the data at this point
puts -nonewline $out [read $in]
close $in
close $out

For larger files, it is better to use the fcopy command, though in general this restricts what operations can be performed rather more (only encoding and end-of-line translations are possible, though not shown here):

set in [open "input.txt" r]
set out [open "output.txt" w]
fcopy $in $out
close $in
close $out

Or the minimal version if we don't need any processing of the data at all:

file copy input.txt output.txt

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

[edit] Toka

This is one method, which works with any type of file:

( source dest -- )
{
value| source dest size buffer |
{
{
[ "W" file.open to dest ] is open-dest
[ "R" file.open to source ] is open-source
[ open-dest open-source ]
} is open-files
{
[ source file.size to size ] is obtain-size
[ size malloc to buffer ] is allocate-buffer
[ obtain-size allocate-buffer ]
} is create-buffer
[ source dest and 0 <> ] is check
[ open-files create-buffer check ]
} is prepare
[ source buffer size file.read drop ] is read-source
[ dest buffer size file.write drop ] is write-dest
[ source file.close dest file.close ] is close-files
[ prepare [ read-source write-dest close-files ] ifTrue ]
} is copy-file

And a much simpler way for plain text files, making use of file.slurp:

[ ( source dest -- ) 
swap file.slurp dup 0 <>
[ >r "W" file.open dup r> string.getLength file.write drop file.close ] ifTrue
] is copy-file

And a test:

" input.txt" " output.txt" copy-file

[edit] UNIX Shell

[edit] Bourne Shell

#!/bin/sh
while read a; do
echo "$a"
done <input.txt >output.txt

Another way, using the 'cat' program

#!/bin/sh
cat input.txt >output.txt

Yet another way, using the 'cp' utility

#!/bin/sh
cp input.txt output.txt

[edit] Ursala

I/O in Ursala is meant to be handled transparently by the run time system. The application is passed the input files as an argument and expected to return the output files as a result.

Returning a copy of the input file with a new name causes it to be written as a new file.

#import std
 
#executable ('parameterized','')
 
fileio = ~command.files; &h.path.&h:= 'output.txt'!

[edit] VBScript

one liner (-2 for system default encoding)

CreateObject("Scripting.FileSystemObject").OpenTextFile("output.txt",2,-2).Write CreateObject("Scripting.FileSystemObject").OpenTextFile("input.txt", 1, -2).ReadAll

[edit] Visual Basic .NET

Works with: Visual Basic .NET version 9.0+

'byte copy
My.Computer.FileSystem.WriteAllBytes("output.txt", _
My.Computer.FileSystem.ReadAllBytes("input.txt"), False)
 
'text copy
Using input = IO.File.OpenText("input.txt"), _
output As New IO.StreamWriter(IO.File.OpenWrite("output.txt"))
output.Write(input.ReadToEnd)
End Using
 
'Line by line text copy
Using input = IO.File.OpenText("input.txt"), _
output As New IO.StreamWriter(IO.File.OpenWrite("output.txt"))
Do Until input.EndOfStream
output.WriteLine(input.ReadLine)
Loop
End Using
Personal tools
Support