File input/output: Difference between revisions

m
(Added solution for Action!)
(31 intermediate revisions by 22 users not shown)
Line 14:
=={{header|11l}}==
 
<langsyntaxhighlight lang="11l">V file_contents = File(‘input.txt’).read()
File(‘output.txt’, ‘w’).write(file_contents)</langsyntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program readwrtFile64.s */
Line 171:
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|ACL2}}==
<langsyntaxhighlight lang="lisp">:set-state-ok t
 
(defun read-channel (channel limit state)
Line 212:
(mv-let (contents state)
(read-from-file in (expt 2 40) state)
(write-to-file out contents state)))</langsyntaxhighlight>
 
=={{header|Action!}}==
The attached result has been obtained under DOS 2.5.
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit
 
PROC Dir(CHAR ARRAY filter)
Line 272:
PrintF("Dir ""%S""%E",filter)
Dir(filter)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/File_input_output.png Screenshot from Atari 8-bit computer]
Line 297:
 
Assuming everything is fine and no error handling is required, this solution is sufficient:
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure Read_And_Write_File_Line_By_Line is
Line 326:
Close (Output);
end if;
end Read_And_Write_File_Line_By_Line;</langsyntaxhighlight>
 
Expanded with proper error handling and reporting it reads:
 
<langsyntaxhighlight 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
Line 380:
Close (Output);
end if;
end Read_And_Write_File_Line_By_Line;</langsyntaxhighlight>
 
===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.)
<langsyntaxhighlight lang="ada">with Ada.Sequential_IO;
 
procedure Read_And_Write_File_Character_By_Character is
Line 410:
Close (Output);
end if;
end Read_And_Write_File_Character_By_Character;</langsyntaxhighlight>
 
===Using Ada.Text_IO.Text_Streams===
Line 416:
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.
 
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;
Line 439:
Close (Output);
end if;
end Using_Text_Streams;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">file i, o;
text s;
 
Line 452:
o.text(s);
o.byte('\n');
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 460:
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68">PROC copy file v1 = (STRING in name, out name)VOID: (
# note: algol68toc-1.18 - can compile, but not run v1 #
INT errno;
Line 505:
test:(
copy file v2("input.txt","output.txt")
)</langsyntaxhighlight>
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">on copyFile from src into dst
set filedata to read file src
set outfile to open for access dst with write permission
Line 515:
end copyFile
 
copyFile from ":input.txt" into ":output.txt"</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 746:
pop {r2,lr}
bx lr
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">source: read "input.txt"
write "output.txt" source
print source</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
Method 1: the input file can be processed line by line.
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop, Read, input.txt, output.txt
FileAppend, %A_LoopReadLine%`n</langsyntaxhighlight>
Method 2: the input file can be read at once if it is less than 1 GB.
<langsyntaxhighlight lang="autohotkey">FileRead, var, input.txt
FileAppend, %var%, output.txt</langsyntaxhighlight>
Method 3: the file can be copied without I/O.
<langsyntaxhighlight lang="autohotkey">FileCopy, input.txt, output.txt</langsyntaxhighlight>
 
Binary I/O is possible with [http://www.autohotkey.com/forum/topic4604.html&highlight=binread this] library from Laszlo.
Line 771:
(This does not handle properly binary files)
 
<langsyntaxhighlight lang="awk">BEGIN {
while ( (getline <"input.txt") > 0 ) {
print >"output.txt"
}
}</langsyntaxhighlight>
 
=={{header|Babel}}==
<langsyntaxhighlight lang="babel">(main
{ "input.txt" >>> -- File is now on stack
foo set -- File is now in 'foo'
foo "output.txt" <<< })</langsyntaxhighlight>
 
The spirit of Babel is to manipulate things on the stack whenever feasible. In this example,
Line 793:
 
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<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>
 
==={{header|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.
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">100 I$ = "INPUT.TXT"
110 O$ = "OUTPUT.TXT"
120 M$ = CHR$(13)
Line 830 ⟶ 819:
300 IF NOT EOF THEN RESUME
310 PRINT M$D$"CLOSE"
</syntaxhighlight>
</lang>
 
==={{header|BaCon}}===
<langsyntaxhighlight lang="freebasic">
text$ = LOAD$("input.txt")
SAVE text$ TO "output.txt"
</syntaxhighlight>
</lang>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">open 1, "input.txt"
open 2, "output.txt"
while not eof(1)
linea$ = readline(1)
write 2, linea$
end while
close 1
close 2</syntaxhighlight>
 
==={{header|BBC BASIC}}===
[[BBC BASIC for Windows]] has a file copy command:
<syntaxhighlight lang="bbcbasic">*COPY input.txt output.txt</syntaxhighlight>
Alternatively the copy can be done explicitly:
<syntaxhighlight lang="bbcbasic">infile% = OPENIN("input.txt")
outfile% = OPENOUT("output.txt")
WHILE NOT EOF#infile%
BPUT #outfile%, BGET#infile%
ENDWHILE
CLOSE #infile%
CLOSE #outfile%</syntaxhighlight>
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight lang="commodorebasic">10 print chr$(14) : rem switch to upper+lower case set
20 print "read seq file input.txt and write to seq file output.txt"
30 open 4,8,4,"input.txt,seq,read"
Line 851 ⟶ 862:
110 close 4
120 close 8
130 end</langsyntaxhighlight>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
/'
input.txt contains:
 
The quick brown fox jumps over the lazy dog.
Empty vessels make most noise.
Too many chefs spoil the broth.
A rolling stone gathers no moss.
'/
 
Open "output.txt" For Output As #1
Open "input.txt" For Input As #2
Dim line_ As String ' note that line is a keyword
 
While Not Eof(2)
Line Input #2, line_
Print #1, line_
Wend
 
Close #2
Close #1</syntaxhighlight>
{{out}}
<pre>
output.txt contains:
 
The quick brown fox jumps over the lazy dog.
Empty vessels make most noise.
Too many chefs spoil the broth.
A rolling stone gathers no moss.
</pre>
 
==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">
 
/*
 
Rosetta Code File input/output example
FutureBasic 7.0.14
 
Rich Love
9/25/22
 
Before running this, use TextEdit to create a file called input.txt on your desktop.
Format as plain text and create a few lines of text.
Then save.
 
*/
 
output file "FileInputOutput.app"
 
CFURLRef ParentDirectory // Create a url for the desktop
ParentDirectory = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask )
 
CFURLRef inputURL // Create a url for input.txt on the desktop
inputURL = fn URLByAppendingPathComponent( ParentDirectory, @"input.txt" )
 
CFURLRef outputURL // Create a url for output.txt on the desktop
outputURL = fn URLByAppendingPathComponent( ParentDirectory, @"output.txt" )
 
open "O", 1, outputURL
open "I", 2, inputURL
 
str255 dataLine
 
While Not Eof(2)
Line Input #2, dataLine
Print #1, dataLine
Wend
 
Close #1
Close #2
 
end
</syntaxhighlight>
 
==={{header|Gambas}}===
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sOutput As String = "Hello "
Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored
 
File.Save(User.Home &/ "output.txt", sOutput)
File.Save(User.Home &/ "input.txt", sOutput & sInput)
 
Print "'input.txt' contains - " & sOutput & sInput
Print "'output.txt' contains - " & sOutput
 
End</syntaxhighlight>
Output:
<pre>
'input.txt' contains - Hello World!
'output.txt' contains - Hello
</pre>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 STRING TX$*254
110 OPEN #1:"output.txt"
120 OPEN #2:"input.txt" ACCESS OUTPUT
Line 867 ⟶ 973:
210 CLOSE #1
220 CLOSE #2
230 END HANDLER</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight 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</syntaxhighlight>
 
==={{header|PureBasic}}===
====Basic file copy====
<syntaxhighlight lang="purebasic">CopyFile("input.txt","output.txt")</syntaxhighlight>
 
====Line by line====
<syntaxhighlight 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</syntaxhighlight>
 
====Reading & writing the complete file in one pass====
<syntaxhighlight 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</syntaxhighlight>
 
==={{header|QBasic}}===
See [[#QuickBASIC|QuickBASIC]].
 
==={{header|QuickBASIC}}===
{{works with|QuickBasic|4.5}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">
' File input/output
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
END
</syntaxhighlight>
 
==={{header|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.
 
<syntaxhighlight 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</syntaxhighlight>
 
When just copying data, the code can be simplified by using the CopyFrom method.<br />
(The second parameter for CopyFrom is number of bytes to copy, 0 = copy the whole file.)
 
<syntaxhighlight 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</syntaxhighlight>
 
==={{header|REALbasic}}===
<syntaxhighlight 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
</syntaxhighlight>
 
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight 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
</syntaxhighlight>
 
Or directly with no intermediate fileData$
{{works with|Just BASIC}}
<syntaxhighlight lang="runbasic">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
</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">OPEN #1: NAME "input.txt", ORG TEXT, ACCESS INPUT, CREATE OLD
OPEN #2: NAME "output.txt", CREATE NEWOLD
ERASE #2
DO
LINE INPUT #1: linea$
PRINT #2: linea$
LOOP UNTIL END #1
CLOSE #1
CLOSE #2
END</syntaxhighlight>
 
==={{header|VBA}}===
<syntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Dim s As String, FF As Integer
 
'read a file line by line
FF = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF
While Not EOF(FF)
Line Input #FF, s
Debug.Print s
Wend
Close #FF
 
'read a file
FF = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF
s = Input(LOF(1), #FF)
Close #FF
Debug.Print s
 
'write a file
FF = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\output.txt" For Output As #FF
Print #FF, s
Close #FF
End Sub</syntaxhighlight>
 
==={{header|VBScript}}===
One liner (-2 for system default encoding)
<syntaxhighlight lang="vb">CreateObject("Scripting.FileSystemObject").OpenTextFile("output.txt",2,-2).Write CreateObject("Scripting.FileSystemObject").OpenTextFile("input.txt", 1, -2).ReadAll</syntaxhighlight>
 
==={{header|Visual Basic .NET}}===
{{works with|Visual Basic .NET|9.0+}}
====Byte copy====
<syntaxhighlight lang="vbnet">My.Computer.FileSystem.WriteAllBytes("output.txt", _
My.Computer.FileSystem.ReadAllBytes("input.txt"), False)
</syntaxhighlight>
 
====Text copy====
<syntaxhighlight lang="vbnet">Using input = IO.File.OpenText("input.txt"), _
output As New IO.StreamWriter(IO.File.OpenWrite("output.txt"))
output.Write(input.ReadToEnd)
End Using</syntaxhighlight>
====Line by line text copy====
<syntaxhighlight lang="vbnet">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</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">open "input.txt" for reading as #1
open "output.txt" for writing as #2
while not eof(1)
line input #1 linea$
print #2 linea$
wend
close #1
close #2</syntaxhighlight>
 
=={{header|Batch File}}==
<syntaxhighlight lang ="dos">copy input.txt output.txt</langsyntaxhighlight>
or
<langsyntaxhighlight lang="dos">type input.txt > output.txt</langsyntaxhighlight>
or
<langsyntaxhighlight lang="dos">for /f "" %L in ('more^<input.txt') do echo %L>>output.txt</langsyntaxhighlight>
 
There may be other techniques too.
 
=={{header|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>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">GET "libhdr"
 
LET start() BE $(
Line 924 ⟶ 1,238:
endwrite()
$)
$)</langsyntaxhighlight>
 
=={{header|Beef}}==
 
<syntaxhighlight lang="csharp">using System;
using System.IO;
 
namespace FileIO
{
class Program
{
static void Main()
{
String s = scope .();
File.ReadAllText("input.txt", s);
File.WriteAllText("output.txt", s);
}
}
}
</syntaxhighlight>
 
 
=={{header|Befunge}}==
{{works with|CCBI|2.1}}
<langsyntaxhighlight lang="befunge">0110"txt.tupni"#@i10"txt.tuptuo"#@o@</langsyntaxhighlight>
 
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).
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">data←•FBytes "input.txt"
"output.txt" •FBytes data</syntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">put$(get$"input.txt","output.txt",NEW)</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int main(int argc, char **argv) {
Line 963 ⟶ 1,301:
fclose(in);
return 0;
}</langsyntaxhighlight>
 
A couple of remarks on the preceding example:
Line 972 ⟶ 1,310:
 
{{works with|POSIX}}
<langsyntaxhighlight lang="c">#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
Line 1,007 ⟶ 1,345:
copy_file("infile", "outfile");
return 0;
}</langsyntaxhighlight>
 
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:<langsyntaxhighlight lang="c">int copy_file(const char *in, const char *out)
{
int ret = 0;
Line 1,031 ⟶ 1,369:
if (bi != (void*)-1) munmap(bi, st.st_size);
return ret;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Line 1,037 ⟶ 1,375:
The long way:
 
<langsyntaxhighlight lang="csharp">using System.IO;
 
using (var reader = new StreamReader("input.txt"))
Line 1,044 ⟶ 1,382:
var text = reader.ReadToEnd();
writer.Write(text);
}</langsyntaxhighlight>
 
The short way:
 
<langsyntaxhighlight lang="csharp">using System.IO;
 
var text = File.ReadAllText("input.txt");
File.WriteAllText("output.txt", text);</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|g++|3.4.2}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <fstream>
#include <string>
Line 1,082 ⟶ 1,420:
}
return 0;
}</langsyntaxhighlight>
 
Simpler version:
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <fstream>
#include <cstdlib>
Line 1,114 ⟶ 1,452:
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
Using istream- and ostream- iterators:
 
<langsyntaxhighlight lang="cpp"># include <algorithm>
# include <fstream>
 
Line 1,127 ⟶ 1,465:
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(ofile));
}</langsyntaxhighlight>
 
Even simpler way:
 
<langsyntaxhighlight lang="cpp">#include <fstream>
 
int main()
Line 1,138 ⟶ 1,476:
std::ofstream output("output.txt");
output << input.rdbuf();
}</langsyntaxhighlight>
 
=={{header|Clean}}==
Define a function that copies the content from one file to another.
 
<langsyntaxhighlight lang="clean">import StdEnv
 
copyFile fromPath toPath world
Line 1,161 ⟶ 1,499:
# toFile = fwrites buffer toFile
| size buffer < bufferSize = (fromFile, toFile) // we're done
= copyData bufferSize fromFile toFile // continue recursively</langsyntaxhighlight>
 
Apply this function to the world to copy a file.
 
<langsyntaxhighlight lang="clean">Start world = copyFile "input.txt" "output.txt" world</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">
(use 'clojure.java.io)
 
(copy (file "input.txt") (file "output.txt"))
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="lisp">
;; simple file writing
(spit "filename.txt" "your content here")
Line 1,180 ⟶ 1,518:
;; simple file reading
(slurp "filename.txt")
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
Line 1,187 ⟶ 1,525:
Flags used for Micro Focus COBOL:
$set ans85 flag"ans85" flagas"s" sequential"line"
<langsyntaxhighlight COBOLlang="cobol"> identification division.
program-id. copyfile.
environment division.
Line 1,226 ⟶ 1,564:
end-read
.
end program copyfile. </langsyntaxhighlight>
===Implementation===
{{works with|OpenCOBOL}}
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. file-io.
 
Line 1,276 ⟶ 1,614:
 
CLOSE in-file, out-file
.</langsyntaxhighlight>
 
===Built-in Subroutines===
{{works with|OpenCOBOL}}
{{works with|Visual COBOL}}
<langsyntaxhighlight lang="cobol">*> Originally from ACUCOBOL-GT
CALL "C$COPY" USING "input.txt", "output.txt", 0</langsyntaxhighlight>
<langsyntaxhighlight lang="cobol">*> Originally from Micro Focus COBOL
CALL "CBL_COPY_FILE" USING "input.txt", "output.txt"</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
 
<langsyntaxhighlight 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></langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 1,297 ⟶ 1,635:
By lines:
 
<langsyntaxhighlight 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))))</langsyntaxhighlight>
 
By arbitrary blocks and for possibly-binary files:
 
<langsyntaxhighlight lang="lisp">(defconstant +buffer-size+ (expt 2 16))
 
(with-open-file (in #p"input.txt" :direction :input
Line 1,316 ⟶ 1,654:
for size = (read-sequence buffer in)
while (plusp size)
do (write-sequence buffer out :end size))))</langsyntaxhighlight>
 
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 <tt>in</tt> should be opened with <tt>:element-type :default</tt>.
Line 1,323 ⟶ 1,661:
{{libheader|Phobos}}
{{works with|D|2}}
<langsyntaxhighlight lang="d">import std.file: copy;
 
void main() {
copy("input.txt", "output.txt");
}</langsyntaxhighlight>
 
very plainly, with an intermediate variable:
<syntaxhighlight lang="d">
<lang d>
void main() {
import std.file;
Line 1,336 ⟶ 1,674:
std.file.write("output.txt", data);
}
</syntaxhighlight>
</lang>
 
via an intermediate buffer variable:
<langsyntaxhighlight lang="d">import std.stdio;
 
int main() {
Line 1,353 ⟶ 1,691:
 
return 0;
}</langsyntaxhighlight>
 
{{libheader|Tango}}
Line 1,359 ⟶ 1,697:
 
Copy the content from one file to another (exceptions are handled by Tango):
<langsyntaxhighlight lang="d">import tango.io.device.File;
 
void main()
Line 1,367 ⟶ 1,705:
to.copy(from).close;
from.close;
}</langsyntaxhighlight>
Or a shorter example without explicitly closing the output file:
<langsyntaxhighlight lang="d">import tango.io.device.File;
 
void main()
Line 1,375 ⟶ 1,713:
auto to = new File("output.txt", File.WriteCreate);
to.copy(new File("input.txt")).close;
}</langsyntaxhighlight>
 
=={{header|DBL}}==
<syntaxhighlight lang="dbl">;
<lang DBL>;
; File Input and output examples for DBL version 4 by Dario B.
;
Line 1,477 ⟶ 1,815:
 
QUIT, CLOSE 1
STOP</langsyntaxhighlight>
{{out}}
<pre>00001Alan Turing London
Line 1,489 ⟶ 1,827:
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ open input input.txt
$ open /write output output.txt
$ loop:
Line 1,497 ⟶ 1,835:
$ done:
$ close input
$ close output</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 1,534 ⟶ 1,872:
'''- Text File I/O -'''
 
<langsyntaxhighlight lang="delphi">var
f : TextFile ;
s : string ;
Line 1,544 ⟶ 1,882:
ReadLn(F,S);
CloseFile(
end;</langsyntaxhighlight>
 
 
Line 1,551 ⟶ 1,889:
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.
 
<langsyntaxhighlight lang="delphi">var
f : File ;
buff : array[1.1024] of byte ;
Line 1,560 ⟶ 1,898:
Blockread(f,Buff,SizeOf(Buff),BytesRead);
CloseFile(f);
end;</langsyntaxhighlight>
 
'''- Typed File I/O -'''
Line 1,566 ⟶ 1,904:
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.
 
<langsyntaxhighlight lang="delphi">type
 
tAddressBook = Record
Line 1,592 ⟶ 1,930:
BlockWrite(f,v,1,bytes);
CloseFile(f);
end;</langsyntaxhighlight>
 
=={{header|DIBOL-11}}==
<syntaxhighlight lang="dibol-11">
<lang DIBOL-11>
START ;Simple File Input and Output
 
Line 1,617 ⟶ 1,955:
 
END
</syntaxhighlight>
</lang>
 
=={{header|E}}==
{{works with|E-on-Java}}
<langsyntaxhighlight lang="e"><file:output.txt>.setText(<file:input.txt>.getText())</langsyntaxhighlight>
 
(This version holds the entire contents in memory.)
Line 1,627 ⟶ 1,965:
=={{header|Eiffel}}==
 
<langsyntaxhighlight lang="eiffel ">class
APPLICATION
 
Line 1,659 ⟶ 1,997:
output_file: PLAIN_TEXT_FILE
 
end</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x :
<langsyntaxhighlight lang="elena">import system'io;
public program()
Line 1,670 ⟶ 2,008:
File.assign("output.txt").saveContent(text);
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
Read in the whole file and write the contents to a new file.
<langsyntaxhighlight Elixirlang="elixir">defmodule FileReadWrite do
def copy(path,new_path) do
case File.read(path) do
Line 1,689 ⟶ 2,027:
end
FileReadWrite.copy("input.txt","output.txt")</langsyntaxhighlight>
 
'''Built in function:'''
<langsyntaxhighlight Elixirlang="elixir">File.cp!("input.txt", "output.txt")</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
 
<syntaxhighlight lang="lisp">(defvar input (with-temp-buffer
(insert-file-contents "input.txt")
(buffer-string)))
 
(with-temp-file "output.txt"
(insert input))
</syntaxhighlight>
 
=={{header|Erlang}}==
 
<langsyntaxhighlight lang="erlang">
-module( file_io ).
 
Line 1,704 ⟶ 2,052:
{ok, Contents} = file:read_file( "input.txt" ),
ok = file:write_file( "output.txt", Contents ).
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
===Read the entire file and then write it===
{{works with|Euphoria|4.0.0}}
<langsyntaxhighlight lang="euphoria">include std/io.e
write_lines("output.txt", read_lines("input.txt"))</langsyntaxhighlight>
 
===Line-by-line reading and writing===
{{works with|Euphoria|any}}
<langsyntaxhighlight lang="euphoria">integer in,out
object line
 
Line 1,729 ⟶ 2,077:
 
close(out)
close(in)</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
Using an intermediate variable for the input file content is not ideomatic in functional programming. Nevertheless...
 
<langsyntaxhighlight lang="fsharp">open System.IO
 
let copyFile fromTextFileName toTextFileName =
Line 1,744 ⟶ 2,092:
copyFile "input.txt" "output.txt"
0
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
Holds entire file content in memory:
<langsyntaxhighlight lang="factor">"input.txt" binary file-contents
"output.txt" binary set-file-contents</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="factor">[
"input.txt" binary <file-reader> &dispose
"output.txt" binary <file-writer> stream-copy
] with-destructors
</syntaxhighlight>
</lang>
Possibly cheating:
<langsyntaxhighlight lang="factor">"input.txt" "output.txt" copy-file</langsyntaxhighlight>
 
=={{header|Forth}}==
Line 1,763 ⟶ 2,111:
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.
 
<langsyntaxhighlight 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 maxstring84 2 pick read-file throw
?dup while
pad swap 3 pick write-file throw
repeat
Line 1,776 ⟶ 2,124:
 
\ Invoke it like this:
s" output.txt" s" input.txt" copy-file</langsyntaxhighlight>
 
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 maxstring84 bytes are copied at a time, andas that is the globalmaximum guaranteed size of "pad" the global 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.
 
A good practice is to ask the user the file name he wants to create like in this short example
<syntaxhighlight lang="text">: INPUT$ ( text -- n n )
pad swap accept pad swap ;
cr ." Enter file name : " 20 INPUT$ w/o create-file throw Value fd-out
Line 1,792 ⟶ 2,140:
s\" \n" fd-out write-file
close-output
bye</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,798 ⟶ 2,146:
It uses the <tt>access="stream"</tt> which is defined in Fortran 2003 standard and should allow to "copy" also binary data easily.
 
<langsyntaxhighlight lang="fortran">program FileIO
 
integer, parameter :: out = 123, in = 124
Line 1,818 ⟶ 2,166:
end if
 
end program FileIO</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
 
/'
input.txt contains:
 
The quick brown fox jumps over the lazy dog.
Empty vessels make most noise.
Too many chefs spoil the broth.
A rolling stone gathers no moss.
'/
 
Open "output.txt" For Output As #1
Open "input.txt" For Input As #2
Dim line_ As String ' note that line is a keyword
 
While Not Eof(2)
Line Input #2, line_
Print #1, line_
Wend
 
Close #2
Close #1</lang>
 
{{out}}
<pre>
output.txt contains:
 
The quick brown fox jumps over the lazy dog.
Empty vessels make most noise.
Too many chefs spoil the broth.
A rolling stone gathers no moss.
</pre>
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
contents = read["file:input.txt"]
w = new Writer["output.txt"]
w.print[contents]
w.close[]
</syntaxhighlight>
</lang>
 
=={{header|Gambas}}==
<lang gambas>Public Sub Main()
Dim sOutput As String = "Hello "
Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored
 
File.Save(User.Home &/ "output.txt", sOutput)
File.Save(User.Home &/ "input.txt", sOutput & sInput)
 
Print "'input.txt' contains - " & sOutput & sInput
Print "'output.txt' contains - " & sOutput
 
End</lang>
Output:
<pre>
'input.txt' contains - Hello World!
'output.txt' contains - Hello
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">CopyFile := function(src, dst)
local f, g, line;
f := InputTextFile(src);
Line 1,895 ⟶ 2,191:
CloseStream(f);
CloseStream(g);
end;</langsyntaxhighlight>
 
=={{header|GML}}==
<syntaxhighlight lang="gml">var file, str;
 
<lang GML>var file, str;
file = file_text_open_read("input.txt");
str = "";
Line 1,916 ⟶ 2,211:
file = file_text_open_write("output.txt");
file_text_write_string(file,str);
file_text_close(file);</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,935 ⟶ 2,230:
fmt.Println(err)
}
}</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,973 ⟶ 2,268:
log.Fatal(err)
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
 
Using File
<langsyntaxhighlight lang="groovy">content = new File('input.txt').text
new File('output.txt').write(content)</langsyntaxhighlight>
 
Using Ant
<langsyntaxhighlight lang="groovy">new AntBuilder().copy(file:'input.txt', toFile:'output.txt', overwrite:true)</langsyntaxhighlight>
 
Buffered
<langsyntaxhighlight lang="groovy">new File('output.txt').withWriter( w ->
new File('input.txt').withReader( r -> w << r }
}</langsyntaxhighlight>
 
=={{header|GUISS}}==
 
<langsyntaxhighlight lang="guiss">Start,My Documents,Rightclick:input.txt,Copy,Menu,Edit,Paste,
Rightclick:Copy of input.txt,Rename,Type:output.txt[enter]</langsyntaxhighlight>
 
=={{header|Haskell}}==
Note: this doesn't keep the file in memory. Buffering is provided by lazy evaluation.
<langsyntaxhighlight lang="haskell">main = readFile "input.txt" >>= writeFile "output.txt"</langsyntaxhighlight>
 
=={{header|hexiscript}}==
<langsyntaxhighlight lang="hexiscript">let in openin "input.txt"
let out openout "output.txt"
while !(catch (let c read char in))
write c out
endwhile
close in; close out</langsyntaxhighlight>
 
=={{header|HicEst}}==
Copy via system call:
<langsyntaxhighlight 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)</langsyntaxhighlight>
Read and write line by line
<langsyntaxhighlight 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
Line 2,017 ⟶ 2,312:
WRITE(FIle=output, ERror=23) buffer ! on error branch to label 23 (not shown)
ENDDO
22 WRITE(FIle=output, CLoSe=1)</langsyntaxhighlight>
Read and write in 1 block
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|i}}==
<langsyntaxhighlight lang="i">software {
file = load("input.txt")
open("output.txt").write(file)
} </langsyntaxhighlight>
 
=={{header|Icon}} and {{header|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().
<langsyntaxhighlight Iconlang="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</langsyntaxhighlight>
 
=={{header|IDL}}==
 
<langsyntaxhighlight lang="idl">; open two LUNs
openw,unit1,'output.txt,/get
openr,unit2,'input.txt',/get
Line 2,052 ⟶ 2,347:
writeu,unit1,buff
; that's all
close,/all</langsyntaxhighlight>
 
=={{header|Io}}==
 
<langsyntaxhighlight lang="io">inf := File with("input.txt") openForReading
outf := File with("output.txt") openForUpdating
 
Line 2,065 ⟶ 2,360:
inf close
outf close
</syntaxhighlight>
</lang>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j"> 'output.txt' (1!:2~ 1!:1)&< 'input.txt'</langsyntaxhighlight>
 
Or using the system library <tt>files</tt>:
 
<langsyntaxhighlight lang="j">require 'files'
'output.txt' (fwrite~ fread) 'input.txt'</langsyntaxhighlight>
 
Note that J will read as many characters from the file as the system reports, for the size of the file. So if the system reports that the file is empty when it is not, J will return an empty result when using this file reading mechanism. (This can happen for "files" which really represent a connection to something else. When this happens, it's usually better to dedicate a [[Execute_a_system_command#J|separate process]] to reading the file.)
Line 2,083 ⟶ 2,378:
Simple version; Files ''may'' be closed automatically by OS, on some systems.
 
<langsyntaxhighlight lang="java">import java.io.*;
 
public class FileIODemo {
Line 2,100 ⟶ 2,395:
}
}
}</langsyntaxhighlight>
 
This version closes both files after without OS intervention.
 
<langsyntaxhighlight lang="java">import java.io.*;
 
public class FileIODemo2 {
Line 2,133 ⟶ 2,428:
}
}
}</langsyntaxhighlight>
 
{{works with|Java|1.4}}
'''Package''' [[nio]]
 
<langsyntaxhighlight lang="java">import java.io.*;
import java.nio.channels.*;
 
Line 2,163 ⟶ 2,458:
}
}
}</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="java">import java.io.*;
public class Test {
public static void main (String[] args) throws IOException {
Line 2,180 ⟶ 2,475:
bw.close();
}
}</langsyntaxhighlight>
{{works with|Java|7+}}
<langsyntaxhighlight lang="java5">import java.nio.file.*;
public class Copy{
public static void main(String[] args) throws Exception{
Line 2,190 ⟶ 2,485:
Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
{{works with|JScript}}
<langsyntaxhighlight lang="javascript">var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2;
var f_in = fso.OpenTextFile('input.txt', ForReading);
Line 2,208 ⟶ 2,503:
 
f_in.Close();
f_out.Close();</langsyntaxhighlight>
 
{{works with|Node.js}}
<langsyntaxhighlight lang="javascript">
var fs = require('fs');
require('util').pump(fs.createReadStream('input.txt', {flags:'r'}), fs.createWriteStream('output.txt', {flags:'w+'}));
</syntaxhighlight>
</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:
<langsyntaxhighlight lang="jq">jq -M --raw-input --raw-output '. as $line | $line' input.txt > output.txt
</syntaxhighlight>
</lang>
 
 
If the input file consists of JSON entities, and if we wish to "pretty print" each, then the following will suffice:<lang jq>
If the input file consists of JSON entities, and if we wish to "pretty print" each, then the following will suffice:<syntaxhighlight lang="jq">
jq -M '. as $line | $line' input.txt > output.txt
</syntaxhighlight>
</lang>
 
Note that the variable, $line, is included in the above programs solely to satisfy the task requirements. In practice, the jq program in both cases would normally be just: `.`
 
=={{header|Julia}}==
Here we read the content of file1 into the variable mystring. Then we write the content of string to file2.
<langsyntaxhighlight Julialang="julia">mystring = read("file1", String)
open(io->write(io, mystring), "file2", "w")</langsyntaxhighlight>
Note however that Julia has a `cp` function to copy the content of a file to another file.
<langsyntaxhighlight lang="julia">cp("file1","file2")</langsyntaxhighlight>
We can also open and close the file handles manually.
<langsyntaxhighlight Julialang="julia">infile = open("file1", "r")
outfile = open("file2", "w")
write(outfile, read(infile, String))
close(outfile)
close(infile)</langsyntaxhighlight>
Here is a one-liner that guarantees that the file handle is closed
even if something goes wrong during the read/write phase.
<langsyntaxhighlight Julialang="julia">open(IO ->write(IO, read("file1", String)), "file2", "w")</langsyntaxhighlight>
 
=={{header|K}}==
<langsyntaxhighlight Klang="k">`output.txt 0:0:`input.txt</langsyntaxhighlight>
 
=={{header|Kotlin}}==
 
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.io.File
Line 2,254 ⟶ 2,552:
val text = File("input.txt").readText()
File("output.txt").writeText(text)
}</langsyntaxhighlight>
 
=={{header|LabVIEW}}==
{{VI snippet}}<br/>
[[File:LabVIEW File IO.png]]
 
=={{header|Lang}}==
===Text-based===
{{libheader|lang-io-module}}
<syntaxhighlight lang="lang">
# Load the IO module
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">"
ln.loadModule(<pathToIO.lm>)
 
$fileIn = [[io]]::fp.openFile(input.txt)
$fileOut = [[io]]::fp.openFile(output.txt)
 
$text = [[io]]::fp.readFile($fileIn)
[[io]]::fp.writeFile($fileOut, $text)
 
[[io]]::fp.closeFile($fileIn)
[[io]]::fp.closeFile($fileOut)
</syntaxhighlight>
 
===Byte-based===
{{libheader|lang-io-module}}
<syntaxhighlight lang="lang">
# Load the IO module
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">"
ln.loadModule(<pathToIO.lm>)
 
$fileIn = [[io]]::fp.openFile(input.txt)
$fileOut = [[io]]::fp.openFile(output.txt)
 
$bytes = [[io]]::fp.readBytes($fileIn)
[[io]]::fp.writeBytes($fileOut, $bytes)
 
[[io]]::fp.closeFile($fileIn)
[[io]]::fp.closeFile($fileOut)
</syntaxhighlight>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: puts(*) . "\n" . ;
: set-file '> swap open ;
: >>contents slurp puts ;
Line 2,267 ⟶ 2,600:
swap set-file 'fdst set fdst fout >>contents fdst close ;
 
'output.txt 'input.txt copy-file</langsyntaxhighlight>
 
=={{header|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>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">----------------------------------------
-- Returns file as ByteArray
-- @param {string} tFile
Line 2,317 ⟶ 2,636:
fp.closeFile()
return true
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">data = getBytes("input.txt")
putBytes("output.txt", data)</langsyntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">Section Header
 
+ name := FILE_IO;
Line 2,354 ⟶ 2,673:
};
};
);</langsyntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">to copy :from :to
openread :from
openwrite :to
Line 2,367 ⟶ 2,686:
end
 
copy "input.txt "output.txt</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
inFile = io.open("input.txt", "r")
data = inFile:read("*all") -- may be abbreviated to "*a";
Line 2,383 ⟶ 2,702:
-- Oneliner version:
io.open("output.txt", "w"):write(io.open("input.txt", "r"):read("*a"))
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
Line 2,398 ⟶ 2,717:
We can edit thousands of lines. Document is a double linked list.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module FileInputOutput {
Edit "Input.txt"
Line 2,409 ⟶ 2,728:
}
FileInputOutput
</syntaxhighlight>
</lang>
===Using Buffer Object===
A buffer expose real pointer (address), so here M(0) is the address of first byte, and Len(m) is the size of buffer in bytes. This buffer is not for code, but for data (no execution allowed).
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Using_Buffer {
M=buffer("Input.txt")
Line 2,430 ⟶ 2,749:
}
Using_Buffer
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
inout:=proc(filename)
local f;
Line 2,439 ⟶ 2,758:
FileTools[Text][WriteFile]("output.txt",f);
end proc;
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">SetDirectory@NotebookDirectory[];
If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ];
CopyFile["input.txt", "output.txt"]</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">inFile = openFile "input.txt"
outFile = createFile "output.txt"
while not EOF inFile do
Line 2,454 ⟶ 2,773:
)
close inFile
close outFile</langsyntaxhighlight>
 
=={{header|Mercury}}==
<langsyntaxhighlight lang="mercury">:- module file_io.
:- interface.
 
Line 2,496 ⟶ 2,815:
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, io.error_message(Error), !IO),
io.set_exit_status(1, !IO).</langsyntaxhighlight>
 
=={{header|mIRC Scripting Language}}==
 
{{works with|mIRC}}
<langsyntaxhighlight lang="mirc">alias Write2FileAndReadIt {
.write myfilename.txt Goodbye Mike!
.echo -a Myfilename.txt contains: $read(myfilename.txt,1)
}</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE FileIO EXPORTS Main;
 
IMPORT IO, Rd, Wr;
Line 2,525 ⟶ 2,844:
Rd.Close(infile);
Wr.Close(outfile);
END FileIO.</langsyntaxhighlight>
 
The code <code><*FATAL ANY*></code> is a pragma that tells the program to die if any exceptions (such as read/write errors) occur.
Line 2,531 ⟶ 2,850:
=={{header|Nanoquery}}==
{{trans|Ursa}}
<langsyntaxhighlight lang="nanoquery">import Nanoquery.IO
input = new(File, "input.txt")
Line 2,540 ⟶ 2,859:
contents = input.readAll()
output.write(contents)</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{works with|Java|7}}
Takes advantage of some of the new path and file handling features of [[Java|Java's]] <tt>java.nio</tt> library.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,572 ⟶ 2,891:
 
return
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
Copying the file directly (without buffer):
<langsyntaxhighlight lang="nim">import os
copyfile("input.txt", "output.txt")</langsyntaxhighlight>
 
Buffer for the entire file:
<langsyntaxhighlight lang="nim">let x = readFile("input.txt")
writeFile("output.txt", x)</langsyntaxhighlight>
 
Line by line:
<langsyntaxhighlight lang="nim">var
i = open("input.txt")
o = open("output.txt", fmWrite)
Line 2,592 ⟶ 2,911:
 
i.close()
o.close()</langsyntaxhighlight>
 
With a fixed sized buffer:
<langsyntaxhighlight lang="nim">const size = 4096
 
var
Line 2,606 ⟶ 2,925:
 
i.close()
o.close()</langsyntaxhighlight>
 
Using memory mapping:
<langsyntaxhighlight lang="nim">import memfiles
 
var
Line 2,619 ⟶ 2,938:
 
i.close()
o.close()</langsyntaxhighlight>
 
=={{header|Nu}}==
<syntaxhighlight lang="nu">
let text = open "input.txt"
$text | save "output.txt"
</syntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use IO;
 
bundle Default {
Line 2,641 ⟶ 2,966:
}
}
}</langsyntaxhighlight>
 
=={{header|Object Pascal}}==
Line 2,648 ⟶ 2,973:
For a more object oriented style one can use a TFilestream:
 
<langsyntaxhighlight lang="pascal">uses
classes;
begin
Line 2,657 ⟶ 2,982:
Free;
end;
end;</langsyntaxhighlight>
 
=={{header|Objective-C}}==
Line 2,663 ⟶ 2,988:
For copying files, using <code>NSFileManager</code> is preferred:
 
<langsyntaxhighlight lang="objc">[[NSFileManager defaultManager] copyItemAtPath:@"input.txt" toPath:@"output.txt" error:NULL];</langsyntaxhighlight>
 
If you want to do it manually:
 
<langsyntaxhighlight lang="objc">NSData *data = [NSData dataWithContentsOfFile:@"input.txt"];
 
[data writeToFile:@"output.txt" atomically:YES];</langsyntaxhighlight>
 
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 <tt>dataWithContentsOfFile:error:</tt> 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. <tt>dataWithContentsOfFile:</tt> will return nil, and sending nil the message <tt>writeTofile:atomically:</tt> does nothing :-)
Line 2,677 ⟶ 3,002:
=={{header|OCaml}}==
By line:
<langsyntaxhighlight lang="ocaml">let () =
let ic = open_in "input.txt" in
let oc = open_out "output.txt" in
Line 2,689 ⟶ 3,014:
close_in ic;
close_out oc;
;;</langsyntaxhighlight>
 
By character:
<langsyntaxhighlight lang="ocaml">let () =
let ic = open_in "input.txt" in
let oc = open_out "output.txt" in
Line 2,703 ⟶ 3,028:
close_in ic;
close_out oc;
;;</langsyntaxhighlight>
 
(Notice that ic and oc, of type ''in_channel'' and ''out_channel'', are buffered)
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">
in = fopen("input.txt", "r", "native");
out = fopen("output.txt", "w","native");
Line 2,736 ⟶ 3,061:
fclose(out);
end
</syntaxhighlight>
</lang>
 
=={{header|Odin}}==
 
<syntaxhighlight lang="odin">package main
 
import "core:os"
 
main :: proc() {
data, ok := os.read_entire_file("input.txt")
defer delete(data)
 
ok = os.write_entire_file("output.txt", data)
}</syntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: fcopy(in, out)
| f g |
File newMode(in, File.BINARY) dup open(File.READ) ->f
Line 2,746 ⟶ 3,084:
while(f >> dup notNull) [ g addChar ] drop
f close g close ;</langsyntaxhighlight>
 
Usage :
<langsyntaxhighlight Oforthlang="oforth">fcopy("input.txt", "output.txt")</langsyntaxhighlight>
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight Progresslang="progress (OpenEdgeopenedge ABLabl)">COPY-LOB FROM FILE "input.txt" TO FILE "output.txt".</langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
class TextFile from Open.file Open.text end
 
Line 2,771 ⟶ 3,109:
{CopyAll In Out}
{Out close}
{In close}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">f=read("filename.in");
write("filename.out", f);</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 2,784 ⟶ 3,122:
 
{{works with|Perl|5.8.8}}
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!";
Line 2,801 ⟶ 3,139:
 
close $fh_in;
close $fh_out;</langsyntaxhighlight>
 
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.
Line 2,808 ⟶ 3,146:
{{libheader|Phix/basics}}
whole file as a single string (safe on small binary files)
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"input.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"rb"<span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">txt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text<span style="color: #0000FF;">(<span style="color: #000000;">fn<span style="color: #0000FF;">)</span>
Line 2,815 ⟶ 3,153:
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">fn<span style="color: #0000FF;">,<span style="color: #000000;">txt<span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">fn<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
line-by-line (text files only)
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">infn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"input.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"r"<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span>
<span style="color: #000000;">outfn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"output.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"w"<span style="color: #0000FF;">)</span>
Line 2,828 ⟶ 3,166:
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">infn<span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">outfn<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
byte-by-byte (safe on binary files)
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #004080;">integer</span> <span style="color: #004080;">byte<span style="color: #0000FF;">,</span>
<span style="color: #000000;">infd</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"input.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"rb"<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span>
Line 2,841 ⟶ 3,179:
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">infd<span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">outfd<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/File_input/output
by Galileo, 10/2022 #/
 
def eof? dup -1 != enddef
 
"input.txt" "r" fopen
"output.txt" "w" fopen
over fgets
eof? while
over fputs
over fgets
eof? endwhile
drop fclose fclose</syntaxhighlight>
 
=={{header|PHP}}==
 
{{works with|PHP|4}}
<langsyntaxhighlight lang="php"><?php
 
if (!$in = fopen('input.txt', 'r')) {
Line 2,863 ⟶ 3,216:
fclose($out);
fclose($in);
?></langsyntaxhighlight>
{{works with|PHP|5}}
<langsyntaxhighlight lang="php"><?php
if ($contents = file_get_contents('input.txt')) {
if (!file_put_contents('output.txt', $contents)) {
Line 2,874 ⟶ 3,227:
echo('Could not open input file.');
}
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
===Using a variable===
<langsyntaxhighlight PicoLisplang="picolisp">(let V (in "input.txt" (till))
(out "output.txt" (prin V)) )</langsyntaxhighlight>
===Skipping intermediate variable===
<langsyntaxhighlight PicoLisplang="picolisp">(in "input.txt"
(out "output.txt"
(echo) ) )</langsyntaxhighlight>
 
=={{header|Pike}}==
===Line by line===
<syntaxhighlight lang="pike">
<lang Pike>
object lines = Stdio.File("input.txt")->line_iterator();
object out = Stdio.File("output.txt", "cw");
foreach(lines; int line_number; string line)
out->write(line + "\n");
</syntaxhighlight>
</lang>
Note that "\r" will be passed on like any other character. If line_iterator is called with the argument 1 it will however run in trim mode, and all "\r"s will be discarded.
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">
declare in file, out file;
 
Line 2,905 ⟶ 3,258:
put file (out) edit (line) (A);
end;
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
Line 2,911 ⟶ 3,264:
Char by char copy:
 
<langsyntaxhighlight 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;</langsyntaxhighlight>
 
Low level block copy:
 
<langsyntaxhighlight lang="pop11">lvars i_file = sysopen('input.txt', 0, true);
lvars o_file = syscreate('output.txt', 1, true);
lvars buff = inits(4096);
Line 2,926 ⟶ 3,279:
while (sysread(i_file, buff, length(buff)) ->> i) > 0 do
syswrite(o_file, buff, i);
endwhile;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Line 2,932 ⟶ 3,285:
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.
<langsyntaxhighlight PowerShelllang="powershell">Get-Content $PWD\input.txt | Out-File $PWD\output.txt</langsyntaxhighlight>
 
Using an alternate cmdlet to write the file
<langsyntaxhighlight PowerShelllang="powershell">Get-Content $PWD\input.txt | Set-Content $PWD\output.txt</langsyntaxhighlight>
 
=={{header|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>
 
=={{header|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).
 
<langsyntaxhighlight lang="python">import shutil
shutil.copyfile('input.txt', 'output.txt')</langsyntaxhighlight>
 
However the following example shows how one would do file I/O of other sorts:
 
<langsyntaxhighlight lang="python">infile = open('input.txt', 'r')
outfile = open('output.txt', 'w')
for line in infile:
outfile.write(line)
outfile.close()
infile.close()</langsyntaxhighlight>
 
This does no error checking. A more robust program would wrap each open with exception handling blocks:
 
<langsyntaxhighlight lang="python">import sys
try:
infile = open('input.txt', 'r')
Line 3,014 ⟶ 3,326:
finally:
infile.close()
outfile.close()</langsyntaxhighlight>
 
In Python 2.6 (or 2.5 if we use ''from __future__ import with_statement'') we can more simply write:
 
<langsyntaxhighlight lang="python">import sys
try:
with open('input.txt') as infile:
Line 3,026 ⟶ 3,338:
except IOError:
print >> sys.stderr, "Some I/O Error occurred"
sys.exit(1)</langsyntaxhighlight>
 
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.
 
=={{header|Quackery}}==
 
Assuming that <code>input.txt</code> exists beforehand, and <code>output.txt</code> does not (so we can safely <code>drop</code> the success flag that file handling words return), and that we want both files to exist afterwards.
 
Quackery does not have variables, so instead we will move the file text to and from the ancillary stack <code>temp</code>, leaving a copy on the top of <code>temp</code>.
 
<syntaxhighlight lang="quackery"> $ "input.txt" sharefile drop
temp put
temp share
$ "output.txt" putfile drop
</syntaxhighlight>
 
=={{header|R}}==
If files are textual we can use <tt>readLines</tt> ("-1" means "read until the end")
 
<langsyntaxhighlight lang="rsplus">src <- file("input.txt", "r")
dest <- file("output.txt", "w")
 
fc <- readLines(src, -1)
writeLines(fc, dest)
close(src); close(dest)</langsyntaxhighlight>
 
If the files are not textual but "generic":
 
<langsyntaxhighlight lang="rsplus">src <- file("input.txt", "rb")
dest <- file("output.txt", "wb")
 
Line 3,048 ⟶ 3,372:
writeBin(v, dest)
}
close(src); close(dest)</langsyntaxhighlight>
 
Another simpler way is to use <tt>file.copy</tt>
 
<langsyntaxhighlight lang="rsplus">file.copy("input.txt", "output.txt", overwrite = FALSE)</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define file-content
(with-input-from-file "input.txt"
Line 3,067 ⟶ 3,391:
(with-output-to-file "output.txt"
(lambda ()
(write file-content)))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 3,075 ⟶ 3,399:
 
{{works with|Rakudo|2016.07}}
<syntaxhighlight lang="raku" perl6line>spurt "output.txt", slurp "input.txt";</langsyntaxhighlight>
 
Otherwise, copying line-by line:
 
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>my $in = open "input.txt";
my $out = open "output.txt", :w;
for $in.lines -> $line {
Line 3,086 ⟶ 3,410:
}
$in.close;
$out.close;</langsyntaxhighlight>
 
=={{header|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.<br />
(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>
 
=={{header|Raven}}==
<langsyntaxhighlight lang="raven">'input.txt' read 'output.txt' write</langsyntaxhighlight>
 
=={{header|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>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">write %output.txt read %input.txt
 
; No line translations:
Line 3,152 ⟶ 3,423:
; Save a web page:
write/binary %output.html read http://rosettacode.org
</syntaxhighlight>
</lang>
 
=={{header|Red}}==
<syntaxhighlight lang="red">
<lang Red>
file: read %input.txt
write %output.txt file</langsyntaxhighlight>
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">with files'
here dup "input.txt" slurp "output.txt" spew</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 3,172 ⟶ 3,443:
The two &nbsp; ''best programming practice'' &nbsp; REXX statements are only needed if there is another calling program in the invocation chain
<br>(which may want to (re-)use the two files just used.
<langsyntaxhighlight lang="rexx">/*REXX program reads a file and copies the contents into an output file (on a line by line basis).*/
iFID = 'input.txt' /*the name of the input file. */
oFID = 'output.txt' /* " " " " output " */
Line 3,183 ⟶ 3,454:
 
call lineout iFID /*close input file, just to be safe.*/ /* ◄■■■■■■ best programming practice.*/
call lineout oFID /* " output " " " " " */ /* ◄■■■■■■ best programming practice.*/</langsyntaxhighlight>
 
===version 2===
Note that this version is limited to files less than one million bytes (and/or possibly virtual memory).
<langsyntaxhighlight 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)
**********************************************************************/
Line 3,194 ⟶ 3,465:
'erase' ofid /* avoid appending */
s=charin(ifid,,1000000) /* read the input file */
Call charout ofid,s /* write to output file */</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
fn1 = "ReadMe.txt"
fn2 = "ReadMe2.txt"
Line 3,217 ⟶ 3,488:
fseek(fp,0,c_filestart)
return nfilesize
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
In general, open both files in binary mode.
 
<langsyntaxhighlight lang="ruby">str = File.open('input.txt', 'rb') {|f| f.read}
File.open('output.txt', 'wb') {|f| f.write str}</langsyntaxhighlight>
 
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 <code>IO.read('| uname')</code> or <code>open('| sh', 'w')</code> would open a subprocess and not a file.)
 
<langsyntaxhighlight 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}</langsyntaxhighlight>
 
To copy a file block by block, use FileUtils from the standard library.
 
<langsyntaxhighlight lang="ruby">require 'fileutils'
FileUtils.copy_file 'input.txt', 'output.txt'</langsyntaxhighlight>
 
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
<lang runbasic>open "input.txt" for input as #in
<syntaxhighlight lang="runbasic">open "input.txt" for input as #in
fileLen = LOF(#in) 'Length Of File
fileData$ = input$(#in, fileLen) 'read entire file
Line 3,247 ⟶ 3,519:
close #out
end
</syntaxhighlight>
 
' orOr directly with no intermediate fileData$
{{works with|Just BASIC}}
 
<syntaxhighlight lang="runbasic">open "input.txt" for input as #in
open "output.txt" for output as #out
fileLen = LOF(#in) 'Length Of File
Line 3,256 ⟶ 3,528:
close #in
close #out
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn main() {
<lang rust>use std::fs::File;
let contents = std::fs::read("input.txt").expect("error reading input.txt");
use std::io::{Read, Write};
std::fs::write("output.txt", contents).expect("error writing output.txt");
 
fn main() {
let mut file = File::open("input.txt").unwrap();
let mut data = Vec::new();
file.read_to_end(&mut data).unwrap();
let mut file = File::create("output.txt").unwrap();
file.write_all(&data).unwrap();
}
</syntaxhighlight>
</lang>
The above program will panic with any sort of error. The following shows proper error handling:
<langsyntaxhighlight lang="rust">use std::fs::File;
use std::io::{self, Read, Write};
use std::path::Path;
Line 3,298 ⟶ 3,564:
writeln!(&mut io::stderr(), "ERROR: {}", msg).expect("Could not write to stdout");
process::exit(code);
}</langsyntaxhighlight>
 
=={{header|S-BASIC}}==
Surprisingly, S-BASIC has no EOF function, so we have to rely on error trapping to signal end of file. S-BASIC stores its error codes at 103H, and we can position a base-located variable there to retrieve it. The result is something of a kludge, but it works. Other S-BASIC preculiarities are explained by the comments.
<syntaxhighlight lang="BASIC">
comment
Preserve file channel #0 (the console) while declaring channels
#2 and #3 as sequential-access ASCII files.
end
files d, sa, sa
var s = string:255
based errcode = integer
base errcode at 103H
 
comment
CP/M expects upper case file names, but S-BASIC does not
automatically convert file name arguments to upper case, so we
have to do that ourself.
end
create "OUTPUT.TXT"
open #1,"INPUT.TXT"
open #2,"OUTPUT.TXT"
 
comment
S-BASIC allows alphanumeric line "numbers" (which are treated simply
as labels) as the target of GOTO and GOSUB statements, but the first
character must be a digit
end
on error goto 9done
 
rem - runtime error code 15 signals read past end of file
while errcode <> 15 do
begin
input3 #1; s
print #2; s
end
 
9done
close #1
close #2
 
end
</syntaxhighlight>
 
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight lang="scala">import java.io.{ FileNotFoundException, PrintWriter }
 
object FileIO extends App {
Line 3,317 ⟶ 3,626:
}
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
Character by character copy<langsyntaxhighlight 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"))
Line 3,333 ⟶ 3,642:
(close-input-port in-file)
(close-output-port out-file)
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
Line 3,340 ⟶ 3,649:
can be used to copy a source file to a destination.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "osfiles.s7i";
 
Line 3,346 ⟶ 3,655:
begin
copyFile("input.txt", "output.txt");
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
Reading the file all at once:
<langsyntaxhighlight lang="sensetalk">put file "input.txt" into fileContents
put fileContents into file "output.txt"</langsyntaxhighlight>
Reading the file line by line:
<langsyntaxhighlight lang="sensetalk">put "input.txt" into inputFile
put "output.txt" into outputFile
 
Line 3,366 ⟶ 3,675:
 
close file inputFile
close file outputFile</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var in = %f'input.txt'.open_r;
var out = %f'output.txt'.open_w;
 
in.each { |line|
out.print(line);
};</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">(File newNamed: 'input.txt' &mode: File Read) sessionDo: [| :in |
(File newNamed: 'output.txt' &mode: File CreateWrite) sessionDo: [| :out |
in >> out]]</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">| in out |
in := FileStream open: 'input.txt' mode: FileStream read.
out := FileStream open: 'output.txt' mode: FileStream write.
Line 3,388 ⟶ 3,697:
whileFalse: [
out nextPut: (in next)
]</langsyntaxhighlight>
 
=={{header|Snabel}}==
Reads the entire file into into a list of buffers before writing and returns number of bytes written.
<langsyntaxhighlight lang="snabel">
let: q Bin list;
'input.txt' rfile read {{@q $1 push} when} for
@q 'output.txt' rwfile write
0 $1 &+ for
</syntaxhighlight>
</lang>
 
Alternative solution for large files with comparable performance to shell cp; also returns number of bytes written.
<langsyntaxhighlight lang="snabel">
let: q Bin list;
let: wq @q fifo;
Line 3,412 ⟶ 3,721:
@q +? {@w &_ for} when
</syntaxhighlight>
</lang>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight lang="snobol4">
input(.input,5,,'input.txt')
output(.output,6,,'output.txt')
while output = input :s(while)
end</langsyntaxhighlight>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "filecopy" )
@( description, "The job is to create a file called 'output.txt', and place in it" )
@( description, "the contents of the file 'input.txt'." )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/File_IO" );
 
pragma software_model( nonstandard );
pragma license( unrestricted );
 
procedure filecopy is
 
begin
if not files.is_readable( "input.txt" ) then
put_line( standard_error, source_info.source_location & ": input file is not readable" );
command_line.set_exit_status( 192 );
return;
end if;
 
-- With standard shell commands
 
cp input.txt output.txt;
 
-- Using built-in capabilities
 
pragma restriction( no_external_commands );
 
declare
inputfile : file_type;
outputfile : file_type;
begin
create( outputfile, out_file, "output.txt" );
open( inputfile, in_file, "input.txt" );
while not end_of_file( inputfile ) loop
put_line( outputfile, get_line( inputfile ) );
end loop;
close( inputfile ) @ ( outputfile );
end;
 
end filecopy;</syntaxhighlight>
 
=={{header|Standard ML}}==
===Reading the whole file at once as a string===
{{works with|SML/NJ|110.59}}
{{works with|Poly/ML|5.9.1}}
<lang sml>fun copyFile (from, to) =
<syntaxhighlight lang="sml">
(* string -> string -> bool *)
fun copyFile from to =
let
val instream = TextIO.openIn from
Line 3,432 ⟶ 3,789:
in
true
end handle _ => false;</langsyntaxhighlight>
===Binary mode using a buffer===
{{works with|Poly/ML|5.9.1}}
{{works with|SML/NJ|110.99.4}}
<syntaxhighlight lang="sml">
fun copyFile from to =
let
val instream = BinIO.openIn from
val outstream = BinIO.openOut to
fun aux () =
let
val buf = BinIO.inputN(instream, 1024)
in
if Word8Vector.length buf = 0
then ()
else (BinIO.output (outstream, buf); aux ())
end
in
(aux (); BinIO.closeIn instream; BinIO.closeOut outstream)
end
</syntaxhighlight>
 
=={{header|Stata}}==
Stata has a [http://www.stata.com/help.cgi?copy copy] command. Here is a way to implement this by reading and writing line by line.
<langsyntaxhighlight lang="stata">program copyfile
file open fin using `1', read text
file open fout using `2', write text replace
Line 3,449 ⟶ 3,826:
end
 
copyfile input.txt output.txt</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 3,457 ⟶ 3,834:
{{works with|tixwish}}
{{works with|tclkit}}
<langsyntaxhighlight 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</langsyntaxhighlight>
For larger files, it is better to use the <tt>fcopy</tt> 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):
<langsyntaxhighlight lang="tcl">set in [open "input.txt" r]
set out [open "output.txt" w]
fcopy $in $out
close $in
close $out</langsyntaxhighlight>
Or the minimal version if we don't need any processing of the data at all:
<langsyntaxhighlight lang="tcl">file copy input.txt output.txt</langsyntaxhighlight>
===Other key file I/O operations===
;Writing a line to a file<nowiki>:</nowiki>
<langsyntaxhighlight 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</langsyntaxhighlight>
;Reading a line from a file<nowiki>:</nowiki>
<langsyntaxhighlight lang="tcl">#open file for reading
set myfile [open "README.TXT" r]
#read something from the file
Line 3,488 ⟶ 3,865:
puts $mydata
#close the file
close $myfile</langsyntaxhighlight>
 
=={{header|Toka}}==
This is one method, which works with any type of file:
 
<langsyntaxhighlight lang="toka">( source dest -- )
{
value| source dest size buffer |
Line 3,514 ⟶ 3,891:
[ source file.close dest file.close ] is close-files
[ prepare [ read-source write-dest close-files ] ifTrue ]
} is copy-file</langsyntaxhighlight>
 
And a much simpler way for plain text files, making use of file.slurp:
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
And a test:
 
<langsyntaxhighlight lang="toka">" input.txt" " output.txt" copy-file</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
ERROR/STOP CREATE ("input.txt", seq-o,-std-)
Line 3,539 ⟶ 3,916:
path2output=FULLNAME(TUSTEP,"output.txt",-std-)
status=WRITE(path2output,contentinput)
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
Line 3,545 ⟶ 3,922:
As a character string:
 
<langsyntaxhighlight lang="txrlisp">(let ((var (file-get-string "input.txt")))
(file-put-string "output.txt" var))</langsyntaxhighlight>
 
As a list of lines:
 
<langsyntaxhighlight lang="txrlisp">(let ((var (file-get-lines "input.txt")))
(file-put-lines "output.txt" var))</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 3,559 ⟶ 3,936:
* Caveat: output.txt will end with a newline, whether or not input.txt ended with one.
 
<langsyntaxhighlight lang="bash">#!/bin/sh
while IFS= read -r a; do
printf '%s\n' "$a"
done <input.txt >output.txt</langsyntaxhighlight>
 
Another way, using the 'cat' program
 
<langsyntaxhighlight lang="bash">#!/bin/sh
cat input.txt >output.txt</langsyntaxhighlight>
 
Yet another way, using the 'cp' utility
<langsyntaxhighlight lang="bash">#!/bin/sh
cp input.txt output.txt</langsyntaxhighlight>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">decl file input output
decl string contents
input.open "input.txt"
Line 3,580 ⟶ 3,957:
output.open "output.txt"
set contents (input.readall)
out contents output</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 3,590 ⟶ 3,967:
Returning a copy of the input file with a new name causes it to be
written as a new file.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
#executable ('parameterized','')
 
fileio = ~command.files; &h.path.&h:= 'output.txt'!</langsyntaxhighlight>
 
=={{header|VBAUxntal}}==
<syntaxhighlight lang="Uxntal">|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1
<lang vb>Option Explicit
|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1
|a0 @File1 &vector $2 &success $2 &stat $2 &delete $1 &append $1 &name $2 &length $2 &read $2 &write $2
|b0 @File2 &vector $2 &success $2 &stat $2 &delete $1 &append $1 &name $2 &length $2 &read $2 &write $2
 
|0100
Sub Main()
;in-file .File1/name DEO2
Dim s As String, FF As Integer
;out-file .File2/name DEO2
 
&loop
'read a file line by line
#0100 .File1/length DEO2k POP
FF = FreeFile
;buffer .File1/read DEO2
Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF
.File1/success DEI2
While Not EOF(FF)
Line Input #FF, s
Debug.Print s
Wend
Close #FF
 
.File2/length DEO2k POP
'read a file
;buffer .File2/write DEO2
FF = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF
s = Input(LOF(1), #FF)
Close #FF
Debug.Print s
 
EQU2 ?&loop
'write a file
FF = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\output.txt" For Output As #FF
Print #FF, s
Close #FF
End Sub</lang>
 
#80 .System/state DEO
=={{header|VBScript}}==
BRK
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>
@in-file "input.txt 00
@out-file "output.txt 00
@buffer $100</syntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight lang="vedit">File_Open("input.txt")
File_Save_As("output.txt", NOMSG)
Buf_Close(NOMSG) </langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
 
<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>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">with infile "input.txt"
with outfile "output.txt"
whilet line (read_line)
prn line</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
 
var contents = File.read("input.txt")
File.create("output.txt") {|file|
file.writeBytes(contents)
}</langsyntaxhighlight>
 
=={{header|XPL0}}==
Usage: fileio <input.txt >output.txt
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int I, C;
char IntermediateVariable;
Line 3,688 ⟶ 4,038:
ChOut(0, C);
until C = $1A; \EOF
]</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var d=File("input.txt").read();
(f:=File("output.txt","w")).write(d); f.close(); // one read, one write copy
File("output.txt").pump(Console); // verify by printing</langsyntaxhighlight>
It might be considered "good form" to immediately close files (rather than wait for the garbage collector to do it) as these are system resources.
<langsyntaxhighlight lang="zkl">var in=File("input.txt"), out=File("output.txt","w");
foreach line in (in) { out.write(line) } // copy line by line
out.close(); // or out=Void and let GC close the file</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fin,fout:=File("input.txt","rb"), File("output.txt","wb"); // copy in chunks, implicit buffer
fin.pump(Data(0d524_287),fout); fin.close(); fout.close();</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">// copy in chunks, let GC close file handles
File("input.txt","rb").pump(Data(0d524_287),File("output.txt","wb"));</langsyntaxhighlight>
In these last two, the implicit buffer (whose size if given by the numbers) is visible inside the pump. Consider this example, which converts input to upper case text on its way to output (the Data() is optional; using it chunks, without, lines):
<langsyntaxhighlight lang="zkl">File("input.txt").pump(Data(),File("output.txt","w"),"text","toUpper");</langsyntaxhighlight>
 
=={{header|Zig}}==
'''Works with:''' 0.10.x, 0.11.x, 0.12.0-dev.1357+10d03acdb
 
<syntaxhighlight lang="zig">const std = @import("std");
 
pub fn main() (error{OutOfMemory} || std.fs.File.OpenError || std.fs.File.ReadError || std.fs.File.WriteError)!void {
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
 
const cwd = std.fs.cwd();
 
var input_file = try cwd.openFile("input.txt", .{ .mode = .read_only });
defer input_file.close();
 
var output_file = try cwd.createFile("output.txt", .{});
defer output_file.close();
 
// Restrict input_file's size to "up to 10 MiB".
var input_file_content = try input_file.readToEndAlloc(allocator, 10 * 1024 * 1024);
defer allocator.free(input_file_content);
 
try output_file.writeAll(input_file_content);
return;
}</syntaxhighlight>
 
{{omit from|EasyLang}}
{{omit from|HTML}}
{{omit from|Order}}
23

edits