File input/output: Difference between revisions
m Spelling/case, as in <http://en.wikipedia.org/wiki/Input/output>. |
jq |
||
Line 1,361: | Line 1,361: | ||
even if something goes wrong during the read/write phase. |
even if something goes wrong during the read/write phase. |
||
<lang Julia>open(IO ->write(IO, open(readall, "file1", "r")), "file2", "w")</lang> |
<lang Julia>open(IO ->write(IO, open(readall, "file1", "r")), "file2", "w")</lang> |
||
=={{header|jq}}== |
|||
If the input file consists of ordinary lines of text, then the lines can be copied verbatim, one by one, as follows: |
|||
<lang jq>jq -M --raw-input --raw-output '. as $line | $line' input.txt > output.txt |
|||
</lang> |
|||
If the input consists of JSON, and if we wish to "pretty print" it, then the following will suffice:<lang jq> |
|||
jq -M '. as $line | $line' input.txt > output.txt |
|||
</lang> |
|||
=={{header|K}}== |
=={{header|K}}== |
Revision as of 02:58, 13 July 2014
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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", via an intermediate variable. In other words, your program will demonstrate: (1) how to read from a file into a variable, and (2) how to write a variable's contents into a file. Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
ACL2
<lang lisp>:set-state-ok t
(defun read-channel (channel limit state)
(mv-let (ch state) (read-char$ channel state) (if (or (null ch) (zp limit)) (let ((state (close-input-channel channel state))) (mv nil state)) (mv-let (so-far state) (read-channel channel (1- limit) state) (mv (cons ch so-far) state)))))
(defun read-from-file (filename limit state)
(mv-let (channel state) (open-input-channel filename :character state) (mv-let (contents state) (read-channel channel limit state) (mv (coerce contents 'string) state))))
(defun write-channel (channel cs state)
(if (endp cs) (close-output-channel channel state) (let ((state (write-byte$ (char-code (first cs)) channel state))) (let ((state (write-channel channel (rest cs) state))) state))))
(defun write-to-file (filename str state)
(mv-let (channel state) (open-output-channel filename :byte state) (write-channel channel (coerce str 'list) state)))
(defun copy-file (in out state)
(mv-let (contents state) (read-from-file in (expt 2 40) state) (write-to-file out contents state)))</lang>
Ada
Line by line
Assuming everything is fine and no error handling is required, this solution is sufficient: <lang ada>with Ada.Text_IO; use Ada.Text_IO;
procedure Read_And_Write_File_Line_By_Line is
Input, Output : File_Type;
begin
Open (File => Input, Mode => In_File, Name => "input.txt"); Create (File => Output, Mode => Out_File, Name => "output.txt"); loop declare Line : String := Get_Line (Input); begin -- You can process the contents of Line here. Put_Line (Output, Line); end; end loop; Close (Input); Close (Output);
exception
when End_Error => if Is_Open(Input) then Close (Input); end if; if Is_Open(Output) then Close (Output); end if;
end Read_And_Write_File_Line_By_Line;</lang>
Expanded with proper error handling and reporting it reads:
<lang ada>with Ada.Command_Line, Ada.Text_IO; use Ada.Command_Line, Ada.Text_IO;
procedure Read_And_Write_File_Line_By_Line is
Read_From : constant String := "input.txt"; Write_To : constant String := "output.txt"; Input, Output : File_Type;
begin
begin Open (File => Input, Mode => In_File, Name => Read_From); exception when others => Put_Line (Standard_Error, "Can not open the file '" & Read_From & "'. Does it exist?"); Set_Exit_Status (Failure); return; end; begin Create (File => Output, Mode => Out_File, Name => Write_To); exception when others => Put_Line (Standard_Error, "Can not create a file named '" & Write_To & "'."); Set_Exit_Status (Failure); return; end; loop declare Line : String := Get_Line (Input); begin -- You can process the contents of Line here. Put_Line (Output, Line); end; end loop; Close (Input); Close (Output);
exception
when End_Error => if Is_Open(Input) then Close (Input); end if; if Is_Open(Output) then Close (Output); end if;
end Read_And_Write_File_Line_By_Line;</lang>
Character by character
The following example reads and writes each file one character at a time. (You should of course add error reporting as in the example above.) <lang ada>with Ada.Sequential_IO;
procedure Read_And_Write_File_Character_By_Character is
package Char_IO is new Ada.Sequential_IO (Character); use Char_IO;
Input, Output : File_Type; Buffer : Character;
begin
Open (File => Input, Mode => In_File, Name => "input.txt"); Create (File => Output, Mode => Out_File, Name => "output.txt"); loop Read (File => Input, Item => Buffer); Write (File => Output, Item => Buffer); end loop; Close (Input); Close (Output);
exception
when End_Error => if Is_Open(Input) then Close (Input); end if; if Is_Open(Output) then Close (Output); end if;
end Read_And_Write_File_Character_By_Character;</lang>
Using Ada.Text_IO.Text_Streams
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.
<lang ada>with Ada.Text_IO; use Ada.Text_IO; with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;
procedure Using_Text_Streams is
Input, Output : File_Type; Buffer : Character;
begin
Open (File => Input, Mode => In_File, Name => "input.txt"); Create (File => Output, Mode => Out_File, Name => "output.txt"); loop Buffer := Character'Input (Stream (Input)); Character'Write (Stream (Output), Buffer); end loop; Close (Input); Close (Output);
exception
when End_Error => if Is_Open(Input) then Close (Input); end if; if Is_Open(Output) then Close (Output); end if;
end Using_Text_Streams;</lang>
Aime
<lang aime>file i, o; text s;
f_open(i, "input.txt", OPEN_READONLY, 0); f_open(o, "output.txt", OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY,
0644);
while (f_line(i, s) ^ -1) {
f_text(o, s); f_byte(o, '\n');
}</lang>
ALGOL 68
<lang algol68>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")
)</lang>
AppleScript
<lang 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"</lang>
AutoHotkey
Method 1: the input file can be processed line by line. <lang AutoHotkey>Loop, Read, input.txt, output.txt
FileAppend, %A_LoopReadLine%`n</lang>
Method 2: the input file can be read at once if it is less than 1 GB. <lang autohotkey>FileRead, var, input.txt FileAppend, %var%, output.txt</lang> Method 3: the file can be copied without I/O. <lang autohotkey>FileCopy, input.txt, output.txt</lang>
Binary I/O is possible with this library from Laszlo.
AWK
(This does not handle properly binary files)
<lang awk>BEGIN {
while ( (getline <"input.txt") > 0 ) { print >"output.txt" }
}</lang>
Babel
<lang babel>(main
{ "input.txt" >>> -- File is now on stack foo set -- File is now in 'foo' foo "output.txt" <<< })</lang>
The spirit of Babel is to manipulate things on the stack whenever feasible. In this example, I showed how to save it into a symbolic variable (foo) but this step would not be necessary for many simple file-processing tasks, such as splitting on newlines or spaces.
Also note that the >>> (slurp) and <<< (spit) operators only handle "small" files - the limit is configurable but the default limit is 100MB. If you want to open very large files or if you need to perform a lot of interactive file I/O, Babel provides operators that wrap the C standard library fopen()/fclose() functions.
BASIC
<lang qbasic> 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</lang>
Applesoft BASIC
This is only meant to copy a sequential text file. It is very unlikely that this works copying a random access text file. <lang ApplesoftBasic>100 I$ = "INPUT.TXT" 110 O$ = "OUTPUT.TXT" 120 D$ = CHR$(4) 130 M$ = CHR$(13) 140 PRINT D$"VERIFY"I$ 150 PRINT D$"OPEN"O$M$D$"CLOSE"O$M$D$"DELETE"O$ 160 PRINT D$"OPEN"O$M$D$"OPEN"I$;
170 PRINT M$D$"READ"I$ 180 ONERR GOTO 250 190 GET C$ 200 POKE 216,0 210 PRINT M$D$"WRITE"O$",B"B 220 IF C$ <> M$ THEN PRINT C$; 230 B = B + 1 240 GOTO 170
250 POKE 216,0 260 IF PEEK(222) <> 5 THEN RESUME 270 PRINT M$D$"CLOSE"I$M$D$"CLOSE"O$ </lang>
Batch File
<lang dos>copy input.txt output.txt</lang> or <lang dos>type input.txt > output.txt</lang> or <lang dos>for /f "" %L in ('more^<input.txt') do echo %L>>output.txt</lang>
There may be other techniques too.
BBC BASIC
BBC BASIC for Windows has a file copy command: <lang bbcbasic> *COPY input.txt output.txt</lang> Alternatively the copy can be done explicitly: <lang bbcbasic> infile% = OPENIN("input.txt")
outfile% = OPENOUT("output.txt") WHILE NOT EOF#infile% BPUT #outfile%, BGET#infile% ENDWHILE CLOSE #infile% CLOSE #outfile%</lang>
Befunge
<lang befunge>0110"txt.tupni"#@i10"txt.tuptuo"#@o@</lang>
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).
Bracmat
<lang bracmat>put$(get$"input.txt","output.txt",NEW)</lang>
C
<lang 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;
}</lang>
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.
The following example addresses those issues. To avoid buffered I/O, it uses open(), read(), write() and close(), which are part of POSIX.
<lang c>#include <unistd.h>
- include <fcntl.h>
- include <sys/types.h>
- include <sys/stat.h>
/* we just return a yes/no status; caller can check errno */ int copy_file(const char *in, const char *out) { int ret = 0; int fin, fout; ssize_t len; char *buf[4096]; /* buffer size, some multiple of block size preferred */ struct stat st;
if ((fin = open(in, O_RDONLY)) == -1) return 0; if (fstat(fin, &st)) goto bail;
/* open output with same permission */ fout = open(out, O_WRONLY|O_CREAT|O_TRUNC, st.st_mode & 0777); if (fout == -1) goto bail;
while ((len = read(fin, buf, 4096)) > 0) write(fout, buf, len);
ret = len ? 0 : 1; /* last read should be 0 */
bail: if (fin != -1) close(fin); if (fout != -1) close(fout); return ret; }
int main() { copy_file("infile", "outfile"); return 0; }</lang>
If it's certain that mapping the whole input file into memory poses no problem (there can be all kinds of problems), this may be the most efficient:<lang c>int copy_file(const char *in, const char *out) { int ret = 0; int fin, fout; char *bi; struct stat st;
if ((fin = open(in, O_RDONLY)) == -1) return 0; if (fstat(fin, &st)) goto bail;
fout = open(out, O_WRONLY|O_CREAT|O_TRUNC, st.st_mode & 0777); if (fout == -1) goto bail;
bi = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fin, 0);
ret = (bi == (void*)-1) ? 0 : (write(fout, bi, st.st_size) == st.st_size);
bail: if (fin != -1) close(fin); if (fout != -1) close(fout); if (bi != (void*)-1) munmap(bi, st.st_size); return ret; }</lang>
C#
The long way:
<lang csharp>using System.IO;
using (var reader = new StreamReader("input.txt")) using (var writer = new StreamWriter("output.txt")) {
var text = reader.ReadToEnd(); writer.Write(text);
}</lang>
The short way:
<lang csharp>using System.IO;
var text = File.ReadAllText("input.txt"); File.WriteAllText("output.txt", text);</lang>
C++
<lang cpp>#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 (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;
}</lang>
Simpler version:
<lang cpp>#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;
}</lang>
Using istream- and ostream- iterators:
<lang cpp># 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));
}</lang>
Even simpler way:
<lang cpp>#include <fstream>
int main() {
std::ifstream input("input.txt"); std::ofstream output("output.txt"); output << input.rdbuf();
}</lang>
Clean
Define a function that copies the content from one file to another.
<lang clean>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</lang>
Apply this function to the world to copy a file.
<lang clean>Start world = copyFile "input.txt" "output.txt" world</lang>
Clojure
<lang lisp> (use 'clojure.java.io)
(copy (file "input.txt") (file "output.txt")) </lang>
<lang lisp>
- simple file writing
(spit "filename.txt" "your content here")
- simple file reading
(slurp "filename.txt") </lang>
COBOL
Implementation
<lang cobol> IDENTIFICATION DIVISION.
PROGRAM-ID. file-io.
ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT in-file ASSIGN "input.txt" ORGANIZATION LINE SEQUENTIAL. SELECT OPTIONAL out-file ASSIGN "output.txt" ORGANIZATION LINE SEQUENTIAL.
DATA DIVISION. FILE SECTION. FD in-file. 01 in-line PIC X(256).
FD out-file. 01 out-line PIC X(256). PROCEDURE DIVISION. DECLARATIVES. in-file-error SECTION. USE AFTER ERROR ON in-file. DISPLAY "An error occurred while using input.txt." GOBACK . out-file-error SECTION. USE AFTER ERROR ON out-file. DISPLAY "An error occurred while using output.txt." GOBACK . END DECLARATIVES.
mainline. OPEN INPUT in-file OPEN OUTPUT out-file
PERFORM FOREVER READ in-file AT END EXIT PERFORM END-READ WRITE out-line FROM in-line END-PERFORM
CLOSE in-file, out-file .</lang>
Built-in Subroutines
<lang cobol>*> Originally from ACUCOBOL-GT CALL "C$COPY" USING "input.txt", "output.txt", 0</lang> <lang cobol>*> Originally from Micro Focus COBOL CALL "CBL_COPY_FILE" USING "input.txt", "output.txt"</lang>
ColdFusion
<lang cfm><cfif fileExists(expandPath("input.txt"))>
<cffile action="read" file="#expandPath('input.txt')#" variable="inputContents"> <cffile action="write" file="#expandPath('output.txt')#" output="#inputContents#">
</cfif></lang>
Common Lisp
By lines:
<lang lisp>(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))))</lang>
By arbitrary blocks and for possibly-binary files:
<lang lisp>(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))))</lang>
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.
D
<lang d>import std.file: copy;
void main() {
copy("input.txt", "output.txt");
}</lang>
via an intermediate buffer variable: <lang d>import std.stdio;
int main() {
auto from = File("input.txt", "rb"); scope(exit) from.close();
auto to = File("output.txt", "wb"); scope(exit) to.close();
foreach(buffer; from.byChunk(new ubyte[4096*1024])) { to.rawWrite(buffer); }
return 0;
}</lang>
Copy the content from one file to another (exceptions are handled by Tango): <lang d>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;
}</lang> Or a shorter example without explicitly closing the output file: <lang d>import tango.io.device.File;
void main() {
auto to = new File("output.txt", File.WriteCreate); to.copy(new File("input.txt")).close;
}</lang>
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 -
<lang delphi>var
f : TextFile ; s : string ;
begin
AssignFile(f,[fully qualified file name); Reset(f); writeln(f,s); Reset(f); ReadLn(F,S); CloseFile(
end;</lang>
- 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.
<lang delphi>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;</lang>
- 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.
<lang delphi>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;</lang>
E
<lang e><file:output.txt>.setText(<file:input.txt>.getText())</lang>
(This version holds the entire contents in memory.)
Eiffel
<lang eiffel >class
APPLICATION
create
make
feature {NONE} -- Initialization
make -- Run application. do create input_file.make_open_read ("input.txt") create output_file.make_open_write ("output.txt")
from input_file.read_character until input_file.exhausted loop output_file.put (input_file.last_character) input_file.read_character end
input_file.close output_file.close end
feature -- Access
input_file: PLAIN_TEXT_FILE output_file: PLAIN_TEXT_FILE
end</lang>
Euphoria
Read the entire file and then write it
<lang euphoria>include std/io.e write_lines("output.txt", read_lines("input.txt"))</lang>
Line-by-line reading and writing
<lang euphoria>integer in,out object line
in = open("input.txt","r") out = open("output.txt","w")
while 1 do
line = gets(in) if atom(line) then -- EOF reached exit end if puts(out,line)
end while
close(out) close(in)</lang>
Erlang
<lang erlang> -module( file_io ).
-export( [task/0] ).
task() ->
{ok, Contents} = file:read_file( "input.txt" ), ok = file:write_file( "output.txt", Contents ).
</lang>
F#
Using an intermediate variable for the input file content is not ideomatic in functional programming. Nevertheless...
<lang fsharp>open System.IO
let copyFile fromTextFileName toTextFileName =
let inputContent = File.ReadAllText fromTextFileName inputContent |> fun text -> File.WriteAllText(toTextFileName, text)
[<EntryPoint>] let main argv =
copyFile "input.txt" "output.txt" 0
</lang>
Factor
Holds entire file content in memory: <lang factor>"input.txt" binary file-contents "output.txt" binary set-file-contents</lang> 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: <lang factor>[
"input.txt" binary <file-reader> &dispose "output.txt" binary <file-writer> stream-copy
] with-destructors </lang> Possibly cheating: <lang factor>"input.txt" "output.txt" copy-file</lang>
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.
<lang forth>\ <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</lang>
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.
Fortran
It uses the access="stream" which is defined in Fortran 2003 standard and should allow to "copy" also binary data easily.
<lang fortran>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</lang>
Frink
<lang frink> contents = read["file:input.txt"] w = new Writer["output.txt"] w.print[contents] w.close[] </lang>
GAP
<lang gap>CopyFile := function(src, dst)
local f, g, line; f := InputTextFile(src); g := OutputTextFile(dst, false); while true do line := ReadLine(f); if line = fail then break else WriteLine(g, Chomp(line)); fi; od; CloseStream(f); CloseStream(g);
end;</lang>
GML
<lang GML>var file, str; file = file_text_open_read("input.txt"); str = ""; while (true)
{ str += file_text_read_string(file); if (file_text_eof(file)) { break; } else { str += chr(vk_enter); file_text_readln(file); } }
file_text_close(file);
file = file_text_open_write("output.txt"); file_text_write_string(file,str); file_text_close(file);</lang>
Go
<lang go>package main
import (
"fmt" "io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Println(err) return } if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { fmt.Println(err) }
}</lang> Alternative solution is not a one-liner, but is one of "secondary interest" that copies data from one file to another without an intermediate variable. <lang go>package main
import (
"io" "log" "os"
)
func CopyFile(out, in string) (err error) {
var inf, outf *os.File inf, err = os.Open(in) if err != nil { return } defer func() { cErr := inf.Close() if err == nil { err = cErr } }() outf, err = os.Create(out) if err != nil { return } _, err = io.Copy(outf, inf) cErr := outf.Close() if err == nil { err = cErr } return
}
func main() {
if err := CopyFile("output.txt", "input.txt"); err != nil { log.Fatal(err) }
}</lang>
Groovy
Using File <lang groovy>new File('output.txt').write(new File('input.txt').text)</lang>
Using Ant <lang groovy>new AntBuilder().copy(file:'input.txt', toFile:'output.txt', overwrite:true)</lang>
Buffered <lang groovy>new File('output.txt').withWriter( w ->
new File('input.txt').withReader( r -> w << r }
}</lang>
GUISS
<lang guiss>Start,My Documents,Rightclick:input.txt,Copy,Menu,Edit,Paste, Rightclick:Copy of input.txt,Rename,Type:output.txt[enter]</lang>
Haskell
Note: this doesn't keep the file in memory. Buffering is provided by lazy evaluation. <lang haskell>main = readFile "input.txt" >>= writeFile "output.txt"</lang>
HicEst
Copy via system call: <lang hicest>CHARACTER input='input.txt ', output='output.txt ', c, buffer*4096 SYSTEM(COPY=input//output, ERror=11) ! on error branch to label 11 (not shown)</lang> Read and write line by line <lang hicest>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)</lang> Read and write in 1 block <lang hicest>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</lang>
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(). <lang 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</lang>
IDL
<lang 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</lang>
Io
<lang io>inf := File with("input.txt") openForReading outf := File with("output.txt") openForUpdating
while(l := inf readLine,
outf write(l, "\n")
)
inf close outf close </lang>
J
<lang j> 'output.txt' (1!:2~ 1!:1)&< 'input.txt'</lang>
Or using the system library files:
<lang j>require 'files' 'output.txt' (fwrite~ fread) 'input.txt'</lang>
Java
Simple version; Files may be closed automatically by OS, on some systems.
<lang java>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(); } }
}</lang>
This version closes both files after without OS intervention.
<lang java>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(); } }
}</lang>
Package nio
<lang java>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 } }
}</lang>
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.
<lang java>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")); String line; while ((line = br.readLine()) != null) { bw.write(line); bw.newLine(); } br.close(); bw.close(); }
}</lang>
<lang java5>import java.nio.file.*; public class Copy{
public static void main(String[] args) throws Exception{ FileSystem fs = FileSystems.getDefault(); Path in = fs.getPath("input.txt"); Path out = fs.getPath("output.txt"); Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING); }
}</lang>
JavaScript
<lang javascript>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();</lang>
<lang javascript> var fs = require('fs'); require('util').pump(fs.createReadStream('input.txt', {flags:'r'}), fs.createWriteStream('output.txt', {flags:'w+'})); </lang>
Julia
Here we read the content of file1 into the variable string. Then we write the content of string to file2. <lang Julia>string = open(readall, "file1", "r") open(io->write(io, string), "file2", "w")</lang> Note however that Julia has a `cp` function to copy the content of a file to another file. <lang julia>cp("file1","file2")</lang> We can also open and close the file handles manually. <lang Julia>infile = open("file1", "r") outfile = open("file2", "w") write(outfile, readall(infile)) close(outfile) close(infile)</lang> Here is a one-liner that guarantee that the file handle is closed even if something goes wrong during the read/write phase. <lang Julia>open(IO ->write(IO, open(readall, "file1", "r")), "file2", "w")</lang>
jq
If the input file consists of ordinary lines of text, then the lines can be copied verbatim, one by one, as follows: <lang jq>jq -M --raw-input --raw-output '. as $line | $line' input.txt > output.txt </lang>
If the input consists of JSON, and if we wish to "pretty print" it, then the following will suffice:<lang jq> jq -M '. as $line | $line' input.txt > output.txt </lang>
K
<lang K>`output.txt 0:0:`input.txt</lang>
LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Lang5
<lang lang5>: puts(*) . "\n" . ;
- set-file '> swap open ;
- >>contents slurp puts ;
- copy-file
swap set-file 'fdst set fdst fout >>contents fdst close ;
'output.txt 'input.txt copy-file</lang>
Liberty BASIC
<lang lb>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</lang>
Lisaac
<lang 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; }; }; };
);</lang>
Logo
<lang logo>to copy :from :to
openread :from openwrite :to setread :from setwrite :to until [eof?] [print readrawline] closeall
end
copy "input.txt "output.txt</lang>
Lua
<lang lua> inFile = io.open("input.txt", "r") data = inFile:read("*all") -- may be abbreviated to "*a";
-- other options are "*line", -- or the number of characters to read.
inFile:close()
outFile = io.open("output.txt", "w") outfile:write(data) outfile:close()
-- Oneliner version: io.open("output.txt", "w"):write(io.open("input.txt", "r"):read("*a")) </lang>
MAXScript
<lang maxscript>inFile = openFile "input.txt" outFile = createFile "output.txt" while not EOF inFile do (
format "%" (readLine inFile) to:outFile
) close inFile close outFile</lang>
Mathematica
<lang Mathematica>SetDirectory@NotebookDirectory[]; If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ]; CopyFile["input.txt", "output.txt"]</lang>
Mercury
<lang mercury>:- module file_io.
- - interface.
- - import_module io.
- - pred main(io::di, io::uo) is det.
- - implementation.
main(!IO) :-
io.open_input("input.txt", InputRes, !IO), ( InputRes = ok(Input), io.read_file_as_string(Input, ReadRes, !IO), ( ReadRes = ok(Contents), io.close_input(Input, !IO), io.open_output("output.txt", OutputRes, !IO), ( OutputRes = ok(Output), io.write_string(Output, Contents, !IO), io.close_output(Output, !IO) ; OutputRes = error(OutputError), print_io_error(OutputError, !IO) ) ; ReadRes = error(_, ReadError), print_io_error(ReadError, !IO) ) ; InputRes = error(InputError), print_io_error(InputError, !IO) ).
- - pred print_io_error(io.error::in, io::di, io::uo) is det.
print_io_error(Error, !IO) :-
io.stderr_stream(Stderr, !IO), io.write_string(Stderr, io.error_message(Error), !IO), io.set_exit_status(1, !IO).</lang>
mIRC Scripting Language
<lang mirc>alias Write2FileAndReadIt { .write myfilename.txt Goodbye Mike! .echo -a Myfilename.txt contains: $read(myfilename.txt,1) }</lang>
Modula-3
<lang modula3>MODULE FileIO EXPORTS Main;
IMPORT IO, Rd, Wr;
<*FATAL ANY*>
VAR
infile: Rd.T; outfile: Wr.T; txt: TEXT;
BEGIN
infile := IO.OpenRead("input.txt"); outfile := IO.OpenWrite("output.txt"); txt := Rd.GetText(infile, LAST(CARDINAL)); Wr.PutText(outfile, txt); Rd.Close(infile); Wr.Close(outfile);
END FileIO.</lang>
The code <*FATAL ANY*>
is a pragma that tells the program to die if any exceptions (such as read/write errors) occur.
NetRexx
Takes advantage of some of the new path and file handling features of Java's java.nio library. <lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols nobinary
import java.nio.
parse arg infileName outfileName .
if infileName = | infileName.length = 0 then infileName = 'data/input.txt' if outfileName = | outfileName.length = 0 then outfileName = 'data/output.txt'
binaryCopy(infileName, outfileName)
return
method binaryCopy(infileName, outfileName) public static
do infile = Paths.get('.', [String infileName]) outfile = Paths.get('.', [String outfileName]) fileOctets = Files.readAllBytes(infile) Files.write(outfile, fileOctets, [StandardOpenOption.WRITE, StandardOpenOption.CREATE])
catch ioex = IOException ioex.printStackTrace() end
return
</lang>
Nimrod
Copying the file directly (without buffer): <lang nimrod>import os copyfile("input.txt", "output.txt")</lang>
Buffer for the entire file: <lang nimrod>let x = readFile("input.txt") writeFile("output.txt", x)</lang>
Line by line: <lang nimrod>var
i = open("input.txt") o = open("output.txt", fmWrite)
for line in i.lines:
o.writeln(line)
i.close() o.close()</lang>
With a fixed sized buffer: <lang nimrod>const size = 4096
var
i = open("input.txt") o = open("output.txt", fmWrite) buf: array[size, char]
while i.readBuffer(buf.addr, size) > 0:
discard o.writeBuffer(buf.addr, size)
i.close() o.close()</lang>
Using memory mapping: <lang nimrod>import memfiles
var
i = memfiles.open("input.txt") o = system.open("output.txt", fmWrite)
var written = o.writeBuffer(i.mem, i.size) assert(written == i.size)
i.close() o.close()</lang>
Objeck
<lang objeck>use IO;
bundle Default {
class Test { function : Main(args : String[]) ~ Nil { len := File->Size("input.txt"); buffer := Byte->New[len]; in := FileReader->New("input.txt"); if(in->IsOpen() <> Nil) { in->ReadBuffer(0, len, buffer); out := FileWriter->New("output.txt"); if(out->IsOpen() <> Nil) { out->WriteBuffer(0, len, buffer); out->Close(); }; in->Close(); }; } }
}</lang>
Objective-C
Read the contents of input.txt and place it in output.txt, creating a file if needed:
<lang objc>NSData *data = [NSData dataWithContentsOfFile:@"input.txt"];
[data writeToFile:@"output.txt" atomically:YES];</lang>
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.
Object Pascal
For procedural code see the Delphi code, which is perfectly fine in ObjectPascal.
For a more object oriented style one can use a TFilestream:
<lang pascal>uses
classes;
begin
with TFileStream.Create('input.txt', fmOpenRead) do try SaveToFile('output.txt'); finally Free; end;
end;</lang>
OCaml
By line: <lang ocaml>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;
- </lang>
By character: <lang ocaml>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;
- </lang>
(Notice that ic and oc, of type in_channel and out_channel, are buffered)
OpenEdge/Progress
<lang Progress (OpenEdge ABL)>COPY-LOB FROM FILE "input.txt" TO FILE "output.txt".</lang>
Oz
<lang 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}</lang>
PARI/GP
<lang parigp>f=read("filename.in"); write("filename.out", f);</lang>
Pascal
The | FreePascal wiki gives a detailed description. For procedureal code see the Delphi examples. The ObjectPascal example is more OO coding style.
Perl
<lang perl>#!/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;</lang>
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.
Perl 6
<lang perl6>my $in = open "input.txt"; my $out = open "output.txt", :w; for $in.lines -> $line { $out.say($line); }</lang>
or, using the new slurp operator:
<lang perl6>(open "output.txt", :w).print(slurp "input.txt")</lang>
PHP
<lang php><?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); ?></lang>
<lang php><?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.');
} ?></lang>
PicoLisp
Using a variable
<lang PicoLisp>(let V (in "input.txt" (till))
(out "output.txt" (prin V)) )</lang>
Skipping intermediate variable
<lang PicoLisp>(in "input.txt"
(out "output.txt" (echo) ) )</lang>
PL/I
<lang pli> 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; </lang>
Pop11
Char by char copy:
<lang pop11>lvars i_stream = discin('input.txt'); lvars o_stream = discout('output.txt'); lvars c; while (i_stream() ->> c) /= termin do
o_stream(c);
endwhile;</lang>
Low level block copy:
<lang pop11>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;</lang>
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. <lang PowerShell>Get-Content $PWD\input.txt | Out-File $PWD\output.txt</lang>
Using an alternate cmdlet to write the file <lang PowerShell>Get-Content $PWD\input.txt | Set-Content $PWD\output.txt</lang>
PureBasic
Basic file copy <lang PureBasic>CopyFile("input.txt","output.txt")</lang>
Line by line
<lang PureBasic>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</lang>
Reading & writing the complete file in one pass
<lang PureBasic>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</lang>
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).
<lang python>import shutil shutil.copyfile('input.txt', 'output.txt')</lang>
However the following example shows how one would do file I/O of other sorts:
<lang python>infile = open('input.txt', 'r') outfile = open('output.txt', 'w') for line in infile:
outfile.write(line)
outfile.close() infile.close()</lang>
This does no error checking. A more robust program would wrap each open with exception handling blocks:
<lang python>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()</lang>
In Python 2.6 (or 2.5 if we use from __future__ import with_statement) we can more simply write:
<lang python>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)</lang>
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.
R
If files are textual we can use readLines ("-1" means "read until the end")
<lang rsplus>src <- file("input.txt", "r") dest <- file("output.txt", "w")
fc <- readLines(src, -1) writeLines(fc, dest) close(src); close(dest)</lang>
If the files are not textual but "generic":
<lang rsplus>src <- file("input.txt", "rb") dest <- file("output.txt", "wb")
while( length(v <- readBin(src, "raw")) > 0 ) {
writeBin(v, dest)
} close(src); close(dest)</lang>
Another simpler way is to use file.copy
<lang rsplus>file.copy("input.txt", "output.txt", overwrite = FALSE)</lang>
Racket
<lang Racket>#lang racket (define file-content
(with-input-from-file "input.txt" (lambda () (let loop ((lst null)) (define new (read-char)) (if (eof-object? new) (apply string lst) (loop (append lst (list new))))))))
(with-output-to-file "output.txt"
(lambda () (write file-content)))</lang>
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.
<lang rapidq>$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</lang>
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.)
<lang rapidq>$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</lang>
Raven
<lang raven>'input.txt' read 'output.txt' write</lang>
REALbasic
<lang vb> Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream Dim tos As TextOutputStream tis = tis.Open(input) tos = tos.Create(output) While Not tis.EOF tos.WriteLine(tis.ReadLine) Wend tis.Close tos.Close
End Sub </lang>
REBOL
<lang 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 </lang>
Retro
<lang Retro>with files' here dup "input.txt" slurp "output.txt" spew</lang>
REXX
In rexx, filename association is used rather than numeric stream numbers and explicit file opening is not required.
Version 1
<lang rexx>/*REXX program to read a file and store the contents into an output file*/
ifid = 'input.txt' /*name of the input file. */ ofid = 'output.txt' /*name of the output file. */ call lineout ofid,,1 /*insure output starts at line 1.*/
do while lines(ifid)\==0 /*read until finished. */ y = linein(ifid) /*read a record from input. */ call lineout ofid,y /*write a record to output.nt. */ end /*stick a fork in it, we're done.*/</lang>
Version 2
<lang rexx>/*REXX program to read a file and store the contents into an output file*/ /*(same as the 1st example, but is faster because no intermediate step.)*/
ifid = 'input.txt' /*name of the input file. */ ofid = 'output.txt' /*name of the output file. */ call lineout ofid,,1 /*insure output starts at line 1.*/
do while lines(ifid)\==0 /*read until finished. */ call lineout ofid, linein(ifid) /*read & write in one statement. */ end /*while*/ /*stick a fork in it, we're done.*/</lang>
Version 3
Note that this version is limited to files less than one million bytes (and/or possibly virtual memory). <lang rexx>/*REXX program to read a file and write contents to an output file*****
- 03.09.2012 Walter Pachl (without erase string would be appended)
- /
ifid='input.txt' /*name of the input file. */ ofid='output.txt' /*name of the output file. */ 'erase' ofid /* avoid appending */ s=charin(ifid,,1000000) /* read the input file */ Call charout ofid,s /* write to output file */</lang>
Ruby
In general, open both files in binary mode.
<lang ruby>str = File.open('input.txt', 'rb') {|f| f.read} File.open('output.txt', 'wb') {|f| f.write str}</lang>
If 'input.txt' is a text file, we may forget binary mode. If no pathname begins with a pipe '|', then we may use IO::read and Kernel#open. (The pipe is a problem, because IO.read('| uname')
or open('| sh', 'w')
would open a subprocess and not a file.)
<lang ruby># Only if 'input.txt' is a text file!
- Only if pipe '|' is not first character of path!
str = IO.read('input.txt') open('output.txt', 'w') {|f| f.write str}</lang>
To copy a file block by block, use FileUtils from the standard library.
<lang ruby>require 'fileutils' FileUtils.copy_file 'input.txt', 'output.txt'</lang>
Run BASIC
<lang runbasic>open "input.txt" for input as #in fileLen = LOF(#in) 'Length Of File fileData$ = input$(#in, fileLen) 'read entire file close #in
open "output.txt" for output as #out print #out, fileData$ 'write entire fie close #out end
' or directly with no intermediate fileData$
open "input.txt" for input as #in open "output.txt" for output as #out fileLen = LOF(#in) 'Length Of File print #out, input$(#in, fileLen) 'entire file close #in close #out </lang>
Rust
<lang rust>extern mod std; use std::io;
fn main() {
let input_file = &Path("input.txt"); let input = io::read_whole_file_str(input_file); match input { Err(e) => fail!(e), Ok(_) => {} }
let output_file = &Path("output.txt"); let output = io::file_writer(output_file, [io::Create, io::Truncate]); match output { Err(e) => fail!(e), Ok(_) => {} }
output.unwrap().write_str(input.unwrap());
}</lang>
Scala
<lang scala>import java.io.{ FileNotFoundException, PrintWriter }
object FileIO extends App {
try { val MyFileTxtTarget = new PrintWriter("output.txt")
scala.io.Source.fromFile("input.txt").getLines().foreach(MyFileTxtTarget.println) MyFileTxtTarget.close() } catch { case e: FileNotFoundException => println(e.getLocalizedMessage()) case e: Throwable => { println("Some other exception type:") e.printStackTrace() } }
}</lang>
Scheme
Character by character copy<lang scheme>; Open ports for the input and output files (define in-file (open-input-file "input.txt")) (define out-file (open-output-file "output.txt"))
- Read and write characters from the input file
- to the output file one by one until end of file
(do ((c (read-char in-file) (read-char in-file)))
((eof-object? c)) (write-char c out-file))
- Close the ports
(close-input-port in-file) (close-output-port out-file) </lang>
Seed7
The library osfiles.s7i contains the function copyFile which can be used to copy a source file to a destination.
<lang seed7>$ include "seed7_05.s7i";
include "osfiles.s7i";
const proc: main is func
begin copyFile("input.txt", "output.txt"); end func;</lang>
Slate
<lang slate>(File newNamed: 'input.txt' &mode: File Read) sessionDo: [| :in |
(File newNamed: 'output.txt' &mode: File CreateWrite) sessionDo: [| :out | in >> out]]</lang>
Smalltalk
<lang 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) ]</lang>
SNOBOL4
<lang snobol4>
input(.input,5,,'input.txt') output(.output,6,,'output.txt')
while output = input :s(while) end</lang>
Standard ML
<lang sml>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;</lang>
Tcl
<lang tcl>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</lang> 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 — or more general byte-level transformations with the generic filter mechanism provided in Tcl 8.6 — none of which are shown here): <lang tcl>set in [open "input.txt" r] set out [open "output.txt" w] fcopy $in $out close $in close $out</lang> Or the minimal version if we don't need any processing of the data at all: <lang tcl>file copy input.txt output.txt</lang>
Other key file I/O operations
- Writing a line to a file:
<lang tcl>#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</lang>
- Reading a line from a file:
<lang tcl>#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</lang>
Toka
This is one method, which works with any type of file:
<lang toka>( 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</lang>
And a much simpler way for plain text files, making use of file.slurp:
<lang toka>[ ( source dest -- )
swap file.slurp dup 0 <> [ >r "W" file.open dup r> string.getLength file.write drop file.close ] ifTrue
] is copy-file</lang>
And a test:
<lang toka>" input.txt" " output.txt" copy-file</lang>
UNIX Shell
Using the 'read' built-in
- Hint: mksh(1) manual says, "If read is run in a loop such as while read foo; do ...; done then leading whitespace will be removed (IFS) and backslashes processed. You might want to use while IFS= read -r foo; do ...; done for pristine I/O."
- Caveat: output.txt will end with a newline, whether or not input.txt ended with one.
<lang bash>#!/bin/sh while IFS= read -r a; do
printf '%s\n' "$a"
done <input.txt >output.txt</lang>
Another way, using the 'cat' program
<lang bash>#!/bin/sh cat input.txt >output.txt</lang>
Yet another way, using the 'cp' utility <lang bash>#!/bin/sh cp input.txt output.txt</lang>
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. <lang Ursala>#import std
- executable ('parameterized',)
fileio = ~command.files; &h.path.&h:= 'output.txt'!</lang>
VBScript
one liner (-2 for system default encoding) <lang vb>CreateObject("Scripting.FileSystemObject").OpenTextFile("output.txt",2,-2).Write CreateObject("Scripting.FileSystemObject").OpenTextFile("input.txt", 1, -2).ReadAll</lang>
Vedit macro language
An edit buffer is normally used as "string variable" in Vedit. To read a file into edit buffer, simply open the file. The file contents can then be modified if required before saving into a new file. <lang vedit>File_Open("input.txt") File_Save_As("output.txt", NOMSG) Buf_Close(NOMSG) </lang>
Visual Basic .NET
<lang vbnet>'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</lang>
Wart
<lang wart>with infile "input.txt"
with outfile "output.txt" whilet line (read_line) prn line</lang>
XPL0
Usage: fileio <input.txt >output.txt
<lang XPL0>include c:\cxpl\codes; int I, C; char IntermediateVariable; [IntermediateVariable:= GetHp; I:= 0; repeat C:= ChIn(1);
IntermediateVariable(I):= C; I:= I+1;
until C = $1A; \EOF I:= 0; repeat C:= IntermediateVariable(I);
I:= I+1; ChOut(0, C);
until C = $1A; \EOF ]</lang>
zkl
<lang zkl>var d=File("input.txt").read(); (f:=File("output.txt","w")).write(d); f.close(); File("output.txt").pump(Console); // verify</lang> Need to close output.txt because it can take the garbage collector a while to notice that the file can be closed. <lang zkl>var in=File("input.txt"), out=File("output.txt","w"); foreach line in (in) { out.write(line) } out.close(); // or out=Void and let GC close the file</lang>
- Programming Tasks
- File handling
- Selection/Short Circuit/Console Program Basics
- ACL2
- Ada
- Aime
- ALGOL 68
- AppleScript
- AutoHotkey
- AWK
- Babel
- BASIC
- Applesoft BASIC
- Batch File
- BBC BASIC
- Befunge
- Bracmat
- C
- C sharp
- C++
- Clean
- Clojure
- COBOL
- ColdFusion
- Common Lisp
- D
- Phobos
- Tango
- Delphi
- E
- Eiffel
- Euphoria
- Erlang
- F Sharp
- Factor
- Forth
- Fortran
- Frink
- GAP
- GML
- Go
- Groovy
- GUISS
- Haskell
- HicEst
- Icon
- Unicon
- IDL
- Io
- J
- Java
- JavaScript
- Julia
- Jq
- K
- LabVIEW
- Lang5
- Liberty BASIC
- Lisaac
- Logo
- Lua
- MAXScript
- Mathematica
- Mercury
- MIRC Scripting Language
- Modula-3
- NetRexx
- Nimrod
- Objeck
- Objective-C
- Object Pascal
- OCaml
- OpenEdge/Progress
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- Pop11
- PowerShell
- PureBasic
- Python
- R
- Racket
- RapidQ
- Raven
- REALbasic
- REBOL
- Retro
- REXX
- Ruby
- Run BASIC
- Rust
- Scala
- Scala Implementations
- Scheme
- Seed7
- Slate
- Smalltalk
- SNOBOL4
- Standard ML
- Tcl
- Toka
- UNIX Shell
- Ursala
- VBScript
- Vedit macro language
- Visual Basic .NET
- Wart
- XPL0
- Zkl
- HTML/Omit
- Order/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- Unlambda/Omit