File input/output: Difference between revisions

Content added Content deleted
(add Zig example)
m (syntax highlighting fixup automation)
Line 14: Line 14:
=={{header|11l}}==
=={{header|11l}}==


<lang 11l>V file_contents = File(‘input.txt’).read()
<syntaxhighlight lang="11l">V file_contents = File(‘input.txt’).read()
File(‘output.txt’, ‘w’).write(file_contents)</lang>
File(‘output.txt’, ‘w’).write(file_contents)</syntaxhighlight>


=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program readwrtFile64.s */
/* program readwrtFile64.s */
Line 171: Line 171:
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang lisp>:set-state-ok t
<syntaxhighlight lang="lisp">:set-state-ok t


(defun read-channel (channel limit state)
(defun read-channel (channel limit state)
Line 212: Line 212:
(mv-let (contents state)
(mv-let (contents state)
(read-from-file in (expt 2 40) state)
(read-from-file in (expt 2 40) state)
(write-to-file out contents state)))</lang>
(write-to-file out contents state)))</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
The attached result has been obtained under DOS 2.5.
The attached result has been obtained under DOS 2.5.
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit


PROC Dir(CHAR ARRAY filter)
PROC Dir(CHAR ARRAY filter)
Line 272: Line 272:
PrintF("Dir ""%S""%E",filter)
PrintF("Dir ""%S""%E",filter)
Dir(filter)
Dir(filter)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/File_input_output.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/File_input_output.png Screenshot from Atari 8-bit computer]
Line 297: Line 297:


Assuming everything is fine and no error handling is required, this solution is sufficient:
Assuming everything is fine and no error handling is required, this solution is sufficient:
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure Read_And_Write_File_Line_By_Line is
procedure Read_And_Write_File_Line_By_Line is
Line 326: Line 326:
Close (Output);
Close (Output);
end if;
end if;
end Read_And_Write_File_Line_By_Line;</lang>
end Read_And_Write_File_Line_By_Line;</syntaxhighlight>


Expanded with proper error handling and reporting it reads:
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;
<syntaxhighlight 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
procedure Read_And_Write_File_Line_By_Line is
Line 380: Line 380:
Close (Output);
Close (Output);
end if;
end if;
end Read_And_Write_File_Line_By_Line;</lang>
end Read_And_Write_File_Line_By_Line;</syntaxhighlight>


===Character by character===
===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.)
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;
<syntaxhighlight lang="ada">with Ada.Sequential_IO;


procedure Read_And_Write_File_Character_By_Character is
procedure Read_And_Write_File_Character_By_Character is
Line 410: Line 410:
Close (Output);
Close (Output);
end if;
end if;
end Read_And_Write_File_Character_By_Character;</lang>
end Read_And_Write_File_Character_By_Character;</syntaxhighlight>


===Using Ada.Text_IO.Text_Streams===
===Using Ada.Text_IO.Text_Streams===
Line 416: 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.
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;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;
with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;
Line 439: Line 439:
Close (Output);
Close (Output);
end if;
end if;
end Using_Text_Streams;</lang>
end Using_Text_Streams;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>file i, o;
<syntaxhighlight lang="aime">file i, o;
text s;
text s;


Line 452: Line 452:
o.text(s);
o.text(s);
o.byte('\n');
o.byte('\n');
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 460: 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]}}
{{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]}}
<lang algol68>PROC copy file v1 = (STRING in name, out name)VOID: (
<syntaxhighlight lang="algol68">PROC copy file v1 = (STRING in name, out name)VOID: (
# note: algol68toc-1.18 - can compile, but not run v1 #
# note: algol68toc-1.18 - can compile, but not run v1 #
INT errno;
INT errno;
Line 505: Line 505:
test:(
test:(
copy file v2("input.txt","output.txt")
copy file v2("input.txt","output.txt")
)</lang>
)</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang applescript>on copyFile from src into dst
<syntaxhighlight lang="applescript">on copyFile from src into dst
set filedata to read file src
set filedata to read file src
set outfile to open for access dst with write permission
set outfile to open for access dst with write permission
Line 515: Line 515:
end copyFile
end copyFile


copyFile from ":input.txt" into ":output.txt"</lang>
copyFile from ":input.txt" into ":output.txt"</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 746: Line 746:
pop {r2,lr}
pop {r2,lr}
bx lr
bx lr
</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>source: read "input.txt"
<syntaxhighlight lang="rebol">source: read "input.txt"
write "output.txt" source
write "output.txt" source
print source</lang>
print source</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Method 1: the input file can be processed line by line.
Method 1: the input file can be processed line by line.
<lang AutoHotkey>Loop, Read, input.txt, output.txt
<syntaxhighlight lang="autohotkey">Loop, Read, input.txt, output.txt
FileAppend, %A_LoopReadLine%`n</lang>
FileAppend, %A_LoopReadLine%`n</syntaxhighlight>
Method 2: the input file can be read at once if it is less than 1 GB.
Method 2: the input file can be read at once if it is less than 1 GB.
<lang autohotkey>FileRead, var, input.txt
<syntaxhighlight lang="autohotkey">FileRead, var, input.txt
FileAppend, %var%, output.txt</lang>
FileAppend, %var%, output.txt</syntaxhighlight>
Method 3: the file can be copied without I/O.
Method 3: the file can be copied without I/O.
<lang autohotkey>FileCopy, input.txt, output.txt</lang>
<syntaxhighlight lang="autohotkey">FileCopy, input.txt, output.txt</syntaxhighlight>


Binary I/O is possible with [http://www.autohotkey.com/forum/topic4604.html&highlight=binread this] library from Laszlo.
Binary I/O is possible with [http://www.autohotkey.com/forum/topic4604.html&highlight=binread this] library from Laszlo.
Line 771: Line 771:
(This does not handle properly binary files)
(This does not handle properly binary files)


<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
while ( (getline <"input.txt") > 0 ) {
while ( (getline <"input.txt") > 0 ) {
print >"output.txt"
print >"output.txt"
}
}
}</lang>
}</syntaxhighlight>


=={{header|Babel}}==
=={{header|Babel}}==
<lang babel>(main
<syntaxhighlight lang="babel">(main
{ "input.txt" >>> -- File is now on stack
{ "input.txt" >>> -- File is now on stack
foo set -- File is now in 'foo'
foo set -- File is now in 'foo'
foo "output.txt" <<< })</lang>
foo "output.txt" <<< })</syntaxhighlight>


The spirit of Babel is to manipulate things on the stack whenever feasible. In this example,
The spirit of Babel is to manipulate things on the stack whenever feasible. In this example,
Line 794: Line 794:
=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
<lang qbasic> OPEN "INPUT.TXT" FOR INPUT AS #1
<syntaxhighlight lang="qbasic"> OPEN "INPUT.TXT" FOR INPUT AS #1
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
DO UNTIL EOF(1)
DO UNTIL EOF(1)
Line 802: Line 802:
CLOSE #1
CLOSE #1
CLOSE #2
CLOSE #2
SYSTEM</lang>
SYSTEM</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{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.
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"
<syntaxhighlight lang="applesoftbasic">100 I$ = "INPUT.TXT"
110 O$ = "OUTPUT.TXT"
110 O$ = "OUTPUT.TXT"
120 M$ = CHR$(13)
120 M$ = CHR$(13)
Line 830: Line 830:
300 IF NOT EOF THEN RESUME
300 IF NOT EOF THEN RESUME
310 PRINT M$D$"CLOSE"
310 PRINT M$D$"CLOSE"
</syntaxhighlight>
</lang>


==={{header|BaCon}}===
==={{header|BaCon}}===
<lang freebasic>
<syntaxhighlight lang="freebasic">
text$ = LOAD$("input.txt")
text$ = LOAD$("input.txt")
SAVE text$ TO "output.txt"
SAVE text$ TO "output.txt"
</syntaxhighlight>
</lang>


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang freebasic>open 1, "input.txt"
<syntaxhighlight lang="freebasic">open 1, "input.txt"
open 2, "output.txt"
open 2, "output.txt"
while not eof(1)
while not eof(1)
Line 846: Line 846:
end while
end while
close 1
close 1
close 2</lang>
close 2</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
<lang commodorebasic>10 print chr$(14) : rem switch to upper+lower case set
<syntaxhighlight 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"
20 print "read seq file input.txt and write to seq file output.txt"
30 open 4,8,4,"input.txt,seq,read"
30 open 4,8,4,"input.txt,seq,read"
Line 861: Line 861:
110 close 4
110 close 4
120 close 8
120 close 8
130 end</lang>
130 end</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 STRING TX$*254
<syntaxhighlight lang="is-basic">100 STRING TX$*254
110 OPEN #1:"output.txt"
110 OPEN #1:"output.txt"
120 OPEN #2:"input.txt" ACCESS OUTPUT
120 OPEN #2:"input.txt" ACCESS OUTPUT
Line 877: Line 877:
210 CLOSE #1
210 CLOSE #1
220 CLOSE #2
220 CLOSE #2
230 END HANDLER</lang>
230 END HANDLER</syntaxhighlight>


==={{header|QBasic}}===
==={{header|QBasic}}===
<lang QBasic>OPEN "INPUT.TXT" FOR INPUT AS #1
<syntaxhighlight lang="qbasic">OPEN "INPUT.TXT" FOR INPUT AS #1
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
DO UNTIL EOF(1)
DO UNTIL EOF(1)
Line 888: Line 888:
CLOSE #1
CLOSE #1
CLOSE #2
CLOSE #2
END</lang>
END</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang qbasic>OPEN #1: NAME "input.txt", ORG TEXT, ACCESS INPUT, CREATE OLD
<syntaxhighlight lang="qbasic">OPEN #1: NAME "input.txt", ORG TEXT, ACCESS INPUT, CREATE OLD
OPEN #2: NAME "output.txt", CREATE NEWOLD
OPEN #2: NAME "output.txt", CREATE NEWOLD
ERASE #2
ERASE #2
Line 900: Line 900:
CLOSE #1
CLOSE #1
CLOSE #2
CLOSE #2
END</lang>
END</syntaxhighlight>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang yabasic>open "input.txt" for reading as #1
<syntaxhighlight lang="yabasic">open "input.txt" for reading as #1
open "output.txt" for writing as #2
open "output.txt" for writing as #2
while not eof(1)
while not eof(1)
Line 910: Line 910:
wend
wend
close #1
close #1
close #2</lang>
close #2</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>copy input.txt output.txt</lang>
<syntaxhighlight lang="dos">copy input.txt output.txt</syntaxhighlight>
or
or
<lang dos>type input.txt > output.txt</lang>
<syntaxhighlight lang="dos">type input.txt > output.txt</syntaxhighlight>
or
or
<lang dos>for /f "" %L in ('more^<input.txt') do echo %L>>output.txt</lang>
<syntaxhighlight lang="dos">for /f "" %L in ('more^<input.txt') do echo %L>>output.txt</syntaxhighlight>


There may be other techniques too.
There may be other techniques too.
Line 923: Line 923:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
[[BBC BASIC for Windows]] has a file copy command:
[[BBC BASIC for Windows]] has a file copy command:
<lang bbcbasic>*COPY input.txt output.txt</lang>
<syntaxhighlight lang="bbcbasic">*COPY input.txt output.txt</syntaxhighlight>
Alternatively the copy can be done explicitly:
Alternatively the copy can be done explicitly:
<lang bbcbasic>infile% = OPENIN("input.txt")
<syntaxhighlight lang="bbcbasic">infile% = OPENIN("input.txt")
outfile% = OPENOUT("output.txt")
outfile% = OPENOUT("output.txt")
WHILE NOT EOF#infile%
WHILE NOT EOF#infile%
Line 931: Line 931:
ENDWHILE
ENDWHILE
CLOSE #infile%
CLOSE #infile%
CLOSE #outfile%</lang>
CLOSE #outfile%</syntaxhighlight>


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>GET "libhdr"
<syntaxhighlight lang="bcpl">GET "libhdr"


LET start() BE $(
LET start() BE $(
Line 967: Line 967:
endwrite()
endwrite()
$)
$)
$)</lang>
$)</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
{{works with|CCBI|2.1}}
{{works with|CCBI|2.1}}
<lang befunge>0110"txt.tupni"#@i10"txt.tuptuo"#@o@</lang>
<syntaxhighlight lang="befunge">0110"txt.tupni"#@i10"txt.tuptuo"#@o@</syntaxhighlight>


This linear program tries to open "input.txt" as text file (or aborts).
This linear program tries to open "input.txt" as text file (or aborts).
Line 977: Line 977:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>put$(get$"input.txt","output.txt",NEW)</lang>
<syntaxhighlight lang="bracmat">put$(get$"input.txt","output.txt",NEW)</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


int main(int argc, char **argv) {
int main(int argc, char **argv) {
Line 1,006: Line 1,006:
fclose(in);
fclose(in);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


A couple of remarks on the preceding example:
A couple of remarks on the preceding example:
Line 1,015: Line 1,015:


{{works with|POSIX}}
{{works with|POSIX}}
<lang c>#include <unistd.h>
<syntaxhighlight lang="c">#include <unistd.h>
#include <fcntl.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/types.h>
Line 1,050: Line 1,050:
copy_file("infile", "outfile");
copy_file("infile", "outfile");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


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)
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:<syntaxhighlight lang="c">int copy_file(const char *in, const char *out)
{
{
int ret = 0;
int ret = 0;
Line 1,074: Line 1,074:
if (bi != (void*)-1) munmap(bi, st.st_size);
if (bi != (void*)-1) munmap(bi, st.st_size);
return ret;
return ret;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Line 1,080: Line 1,080:
The long way:
The long way:


<lang csharp>using System.IO;
<syntaxhighlight lang="csharp">using System.IO;


using (var reader = new StreamReader("input.txt"))
using (var reader = new StreamReader("input.txt"))
Line 1,087: Line 1,087:
var text = reader.ReadToEnd();
var text = reader.ReadToEnd();
writer.Write(text);
writer.Write(text);
}</lang>
}</syntaxhighlight>


The short way:
The short way:


<lang csharp>using System.IO;
<syntaxhighlight lang="csharp">using System.IO;


var text = File.ReadAllText("input.txt");
var text = File.ReadAllText("input.txt");
File.WriteAllText("output.txt", text);</lang>
File.WriteAllText("output.txt", text);</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
{{works with|g++|3.4.2}}
{{works with|g++|3.4.2}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <fstream>
#include <fstream>
#include <string>
#include <string>
Line 1,125: Line 1,125:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


Simpler version:
Simpler version:


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <fstream>
#include <fstream>
#include <cstdlib>
#include <cstdlib>
Line 1,157: Line 1,157:
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>


Using istream- and ostream- iterators:
Using istream- and ostream- iterators:


<lang cpp># include <algorithm>
<syntaxhighlight lang="cpp"># include <algorithm>
# include <fstream>
# include <fstream>


Line 1,170: Line 1,170:
std::istreambuf_iterator<char>(),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(ofile));
std::ostreambuf_iterator<char>(ofile));
}</lang>
}</syntaxhighlight>


Even simpler way:
Even simpler way:


<lang cpp>#include <fstream>
<syntaxhighlight lang="cpp">#include <fstream>


int main()
int main()
Line 1,181: Line 1,181:
std::ofstream output("output.txt");
std::ofstream output("output.txt");
output << input.rdbuf();
output << input.rdbuf();
}</lang>
}</syntaxhighlight>


=={{header|Clean}}==
=={{header|Clean}}==
Define a function that copies the content from one file to another.
Define a function that copies the content from one file to another.


<lang clean>import StdEnv
<syntaxhighlight lang="clean">import StdEnv


copyFile fromPath toPath world
copyFile fromPath toPath world
Line 1,204: Line 1,204:
# toFile = fwrites buffer toFile
# toFile = fwrites buffer toFile
| size buffer < bufferSize = (fromFile, toFile) // we're done
| size buffer < bufferSize = (fromFile, toFile) // we're done
= copyData bufferSize fromFile toFile // continue recursively</lang>
= copyData bufferSize fromFile toFile // continue recursively</syntaxhighlight>


Apply this function to the world to copy a file.
Apply this function to the world to copy a file.


<lang clean>Start world = copyFile "input.txt" "output.txt" world</lang>
<syntaxhighlight lang="clean">Start world = copyFile "input.txt" "output.txt" world</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(use 'clojure.java.io)
(use 'clojure.java.io)


(copy (file "input.txt") (file "output.txt"))
(copy (file "input.txt") (file "output.txt"))
</syntaxhighlight>
</lang>


<lang lisp>
<syntaxhighlight lang="lisp">
;; simple file writing
;; simple file writing
(spit "filename.txt" "your content here")
(spit "filename.txt" "your content here")
Line 1,223: Line 1,223:
;; simple file reading
;; simple file reading
(slurp "filename.txt")
(slurp "filename.txt")
</syntaxhighlight>
</lang>


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 1,230: Line 1,230:
Flags used for Micro Focus COBOL:
Flags used for Micro Focus COBOL:
$set ans85 flag"ans85" flagas"s" sequential"line"
$set ans85 flag"ans85" flagas"s" sequential"line"
<lang COBOL> identification division.
<syntaxhighlight lang="cobol"> identification division.
program-id. copyfile.
program-id. copyfile.
environment division.
environment division.
Line 1,269: Line 1,269:
end-read
end-read
.
.
end program copyfile. </lang>
end program copyfile. </syntaxhighlight>
===Implementation===
===Implementation===
{{works with|OpenCOBOL}}
{{works with|OpenCOBOL}}
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. file-io.
PROGRAM-ID. file-io.


Line 1,319: Line 1,319:


CLOSE in-file, out-file
CLOSE in-file, out-file
.</lang>
.</syntaxhighlight>


===Built-in Subroutines===
===Built-in Subroutines===
{{works with|OpenCOBOL}}
{{works with|OpenCOBOL}}
{{works with|Visual COBOL}}
{{works with|Visual COBOL}}
<lang cobol>*> Originally from ACUCOBOL-GT
<syntaxhighlight lang="cobol">*> Originally from ACUCOBOL-GT
CALL "C$COPY" USING "input.txt", "output.txt", 0</lang>
CALL "C$COPY" USING "input.txt", "output.txt", 0</syntaxhighlight>
<lang cobol>*> Originally from Micro Focus COBOL
<syntaxhighlight lang="cobol">*> Originally from Micro Focus COBOL
CALL "CBL_COPY_FILE" USING "input.txt", "output.txt"</lang>
CALL "CBL_COPY_FILE" USING "input.txt", "output.txt"</syntaxhighlight>


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==


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


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 1,340: Line 1,340:
By lines:
By lines:


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


By arbitrary blocks and for possibly-binary files:
By arbitrary blocks and for possibly-binary files:


<lang lisp>(defconstant +buffer-size+ (expt 2 16))
<syntaxhighlight lang="lisp">(defconstant +buffer-size+ (expt 2 16))


(with-open-file (in #p"input.txt" :direction :input
(with-open-file (in #p"input.txt" :direction :input
Line 1,359: Line 1,359:
for size = (read-sequence buffer in)
for size = (read-sequence buffer in)
while (plusp size)
while (plusp size)
do (write-sequence buffer out :end size))))</lang>
do (write-sequence buffer out :end size))))</syntaxhighlight>


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>.
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,366: Line 1,366:
{{libheader|Phobos}}
{{libheader|Phobos}}
{{works with|D|2}}
{{works with|D|2}}
<lang d>import std.file: copy;
<syntaxhighlight lang="d">import std.file: copy;


void main() {
void main() {
copy("input.txt", "output.txt");
copy("input.txt", "output.txt");
}</lang>
}</syntaxhighlight>


very plainly, with an intermediate variable:
very plainly, with an intermediate variable:
<syntaxhighlight lang="d">
<lang d>
void main() {
void main() {
import std.file;
import std.file;
Line 1,379: Line 1,379:
std.file.write("output.txt", data);
std.file.write("output.txt", data);
}
}
</syntaxhighlight>
</lang>


via an intermediate buffer variable:
via an intermediate buffer variable:
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


int main() {
int main() {
Line 1,396: Line 1,396:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{libheader|Tango}}
{{libheader|Tango}}
Line 1,402: Line 1,402:


Copy the content from one file to another (exceptions are handled by Tango):
Copy the content from one file to another (exceptions are handled by Tango):
<lang d>import tango.io.device.File;
<syntaxhighlight lang="d">import tango.io.device.File;


void main()
void main()
Line 1,410: Line 1,410:
to.copy(from).close;
to.copy(from).close;
from.close;
from.close;
}</lang>
}</syntaxhighlight>
Or a shorter example without explicitly closing the output file:
Or a shorter example without explicitly closing the output file:
<lang d>import tango.io.device.File;
<syntaxhighlight lang="d">import tango.io.device.File;


void main()
void main()
Line 1,418: Line 1,418:
auto to = new File("output.txt", File.WriteCreate);
auto to = new File("output.txt", File.WriteCreate);
to.copy(new File("input.txt")).close;
to.copy(new File("input.txt")).close;
}</lang>
}</syntaxhighlight>


=={{header|DBL}}==
=={{header|DBL}}==
<syntaxhighlight lang="dbl">;
<lang DBL>;
; File Input and output examples for DBL version 4 by Dario B.
; File Input and output examples for DBL version 4 by Dario B.
;
;
Line 1,520: Line 1,520:


QUIT, CLOSE 1
QUIT, CLOSE 1
STOP</lang>
STOP</syntaxhighlight>
{{out}}
{{out}}
<pre>00001Alan Turing London
<pre>00001Alan Turing London
Line 1,532: Line 1,532:


=={{header|DCL}}==
=={{header|DCL}}==
<lang DCL>$ open input input.txt
<syntaxhighlight lang="dcl">$ open input input.txt
$ open /write output output.txt
$ open /write output output.txt
$ loop:
$ loop:
Line 1,540: Line 1,540:
$ done:
$ done:
$ close input
$ close input
$ close output</lang>
$ close output</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 1,577: Line 1,577:
'''- Text File I/O -'''
'''- Text File I/O -'''


<lang delphi>var
<syntaxhighlight lang="delphi">var
f : TextFile ;
f : TextFile ;
s : string ;
s : string ;
Line 1,587: Line 1,587:
ReadLn(F,S);
ReadLn(F,S);
CloseFile(
CloseFile(
end;</lang>
end;</syntaxhighlight>




Line 1,594: Line 1,594:
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.
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
<syntaxhighlight lang="delphi">var
f : File ;
f : File ;
buff : array[1.1024] of byte ;
buff : array[1.1024] of byte ;
Line 1,603: Line 1,603:
Blockread(f,Buff,SizeOf(Buff),BytesRead);
Blockread(f,Buff,SizeOf(Buff),BytesRead);
CloseFile(f);
CloseFile(f);
end;</lang>
end;</syntaxhighlight>


'''- Typed File I/O -'''
'''- Typed File I/O -'''
Line 1,609: Line 1,609:
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.
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
<syntaxhighlight lang="delphi">type


tAddressBook = Record
tAddressBook = Record
Line 1,635: Line 1,635:
BlockWrite(f,v,1,bytes);
BlockWrite(f,v,1,bytes);
CloseFile(f);
CloseFile(f);
end;</lang>
end;</syntaxhighlight>


=={{header|DIBOL-11}}==
=={{header|DIBOL-11}}==
<syntaxhighlight lang="dibol-11">
<lang DIBOL-11>
START ;Simple File Input and Output
START ;Simple File Input and Output


Line 1,660: Line 1,660:


END
END
</syntaxhighlight>
</lang>


=={{header|E}}==
=={{header|E}}==
{{works with|E-on-Java}}
{{works with|E-on-Java}}
<lang e><file:output.txt>.setText(<file:input.txt>.getText())</lang>
<syntaxhighlight lang="e"><file:output.txt>.setText(<file:input.txt>.getText())</syntaxhighlight>


(This version holds the entire contents in memory.)
(This version holds the entire contents in memory.)
Line 1,670: Line 1,670:
=={{header|Eiffel}}==
=={{header|Eiffel}}==


<lang eiffel >class
<syntaxhighlight lang="eiffel ">class
APPLICATION
APPLICATION


Line 1,702: Line 1,702:
output_file: PLAIN_TEXT_FILE
output_file: PLAIN_TEXT_FILE


end</lang>
end</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import system'io;
<syntaxhighlight lang="elena">import system'io;
public program()
public program()
Line 1,713: Line 1,713:
File.assign("output.txt").saveContent(text);
File.assign("output.txt").saveContent(text);
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
Read in the whole file and write the contents to a new file.
Read in the whole file and write the contents to a new file.
<lang Elixir>defmodule FileReadWrite do
<syntaxhighlight lang="elixir">defmodule FileReadWrite do
def copy(path,new_path) do
def copy(path,new_path) do
case File.read(path) do
case File.read(path) do
Line 1,732: Line 1,732:
end
end
FileReadWrite.copy("input.txt","output.txt")</lang>
FileReadWrite.copy("input.txt","output.txt")</syntaxhighlight>


'''Built in function:'''
'''Built in function:'''
<lang Elixir>File.cp!("input.txt", "output.txt")</lang>
<syntaxhighlight lang="elixir">File.cp!("input.txt", "output.txt")</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==


<lang lisp>(defvar input (with-temp-buffer
<syntaxhighlight lang="lisp">(defvar input (with-temp-buffer
(insert-file-contents "input.txt")
(insert-file-contents "input.txt")
(buffer-string)))
(buffer-string)))
Line 1,745: Line 1,745:
(with-temp-file "output.txt"
(with-temp-file "output.txt"
(insert input))
(insert input))
</syntaxhighlight>
</lang>


=={{header|Erlang}}==
=={{header|Erlang}}==


<lang erlang>
<syntaxhighlight lang="erlang">
-module( file_io ).
-module( file_io ).


Line 1,757: Line 1,757:
{ok, Contents} = file:read_file( "input.txt" ),
{ok, Contents} = file:read_file( "input.txt" ),
ok = file:write_file( "output.txt", Contents ).
ok = file:write_file( "output.txt", Contents ).
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
===Read the entire file and then write it===
===Read the entire file and then write it===
{{works with|Euphoria|4.0.0}}
{{works with|Euphoria|4.0.0}}
<lang euphoria>include std/io.e
<syntaxhighlight lang="euphoria">include std/io.e
write_lines("output.txt", read_lines("input.txt"))</lang>
write_lines("output.txt", read_lines("input.txt"))</syntaxhighlight>


===Line-by-line reading and writing===
===Line-by-line reading and writing===
{{works with|Euphoria|any}}
{{works with|Euphoria|any}}
<lang euphoria>integer in,out
<syntaxhighlight lang="euphoria">integer in,out
object line
object line


Line 1,782: Line 1,782:


close(out)
close(out)
close(in)</lang>
close(in)</syntaxhighlight>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
Using an intermediate variable for the input file content is not ideomatic in functional programming. Nevertheless...
Using an intermediate variable for the input file content is not ideomatic in functional programming. Nevertheless...


<lang fsharp>open System.IO
<syntaxhighlight lang="fsharp">open System.IO


let copyFile fromTextFileName toTextFileName =
let copyFile fromTextFileName toTextFileName =
Line 1,797: Line 1,797:
copyFile "input.txt" "output.txt"
copyFile "input.txt" "output.txt"
0
0
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
Holds entire file content in memory:
Holds entire file content in memory:
<lang factor>"input.txt" binary file-contents
<syntaxhighlight lang="factor">"input.txt" binary file-contents
"output.txt" binary set-file-contents</lang>
"output.txt" binary set-file-contents</syntaxhighlight>
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:
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>[
<syntaxhighlight lang="factor">[
"input.txt" binary <file-reader> &dispose
"input.txt" binary <file-reader> &dispose
"output.txt" binary <file-writer> stream-copy
"output.txt" binary <file-writer> stream-copy
] with-destructors
] with-destructors
</syntaxhighlight>
</lang>
Possibly cheating:
Possibly cheating:
<lang factor>"input.txt" "output.txt" copy-file</lang>
<syntaxhighlight lang="factor">"input.txt" "output.txt" copy-file</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
Line 1,816: Line 1,816:
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.
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
<syntaxhighlight lang="forth">\ <to> <from> copy-file
: copy-file ( a1 n1 a2 n2 -- )
: copy-file ( a1 n1 a2 n2 -- )
r/o open-file throw >r
r/o open-file throw >r
Line 1,829: Line 1,829:


\ Invoke it like this:
\ Invoke it like this:
s" output.txt" s" input.txt" copy-file</lang>
s" output.txt" s" input.txt" copy-file</syntaxhighlight>


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.
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.
Line 1,836: Line 1,836:


A good practice is to ask the user the file name he wants to create like in this short example
A good practice is to ask the user the file name he wants to create like in this short example
<lang>: INPUT$ ( text -- n n )
<syntaxhighlight lang="text">: INPUT$ ( text -- n n )
pad swap accept pad swap ;
pad swap accept pad swap ;
cr ." Enter file name : " 20 INPUT$ w/o create-file throw Value fd-out
cr ." Enter file name : " 20 INPUT$ w/o create-file throw Value fd-out
Line 1,845: Line 1,845:
s\" \n" fd-out write-file
s\" \n" fd-out write-file
close-output
close-output
bye</lang>
bye</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 1,851: Line 1,851:
It uses the <tt>access="stream"</tt> which is defined in Fortran 2003 standard and should allow to "copy" also binary data easily.
It uses the <tt>access="stream"</tt> which is defined in Fortran 2003 standard and should allow to "copy" also binary data easily.


<lang fortran>program FileIO
<syntaxhighlight lang="fortran">program FileIO


integer, parameter :: out = 123, in = 124
integer, parameter :: out = 123, in = 124
Line 1,871: Line 1,871:
end if
end if


end program FileIO</lang>
end program FileIO</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


/'
/'
Line 1,895: Line 1,895:


Close #2
Close #2
Close #1</lang>
Close #1</syntaxhighlight>


{{out}}
{{out}}
Line 1,908: Line 1,908:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang="frink">
contents = read["file:input.txt"]
contents = read["file:input.txt"]
w = new Writer["output.txt"]
w = new Writer["output.txt"]
w.print[contents]
w.print[contents]
w.close[]
w.close[]
</syntaxhighlight>
</lang>


=={{header|Gambas}}==
=={{header|Gambas}}==
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sOutput As String = "Hello "
Dim sOutput As String = "Hello "
Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored
Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored
Line 1,926: Line 1,926:
Print "'output.txt' contains - " & sOutput
Print "'output.txt' contains - " & sOutput


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,934: Line 1,934:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>CopyFile := function(src, dst)
<syntaxhighlight lang="gap">CopyFile := function(src, dst)
local f, g, line;
local f, g, line;
f := InputTextFile(src);
f := InputTextFile(src);
Line 1,948: Line 1,948:
CloseStream(f);
CloseStream(f);
CloseStream(g);
CloseStream(g);
end;</lang>
end;</syntaxhighlight>


=={{header|GML}}==
=={{header|GML}}==


<lang GML>var file, str;
<syntaxhighlight lang="gml">var file, str;
file = file_text_open_read("input.txt");
file = file_text_open_read("input.txt");
str = "";
str = "";
Line 1,969: Line 1,969:
file = file_text_open_write("output.txt");
file = file_text_open_write("output.txt");
file_text_write_string(file,str);
file_text_write_string(file,str);
file_text_close(file);</lang>
file_text_close(file);</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,988: Line 1,988:
fmt.Println(err)
fmt.Println(err)
}
}
}</lang>
}</syntaxhighlight>
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.
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
<syntaxhighlight lang="go">package main


import (
import (
Line 2,026: Line 2,026:
log.Fatal(err)
log.Fatal(err)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==


Using File
Using File
<lang groovy>content = new File('input.txt').text
<syntaxhighlight lang="groovy">content = new File('input.txt').text
new File('output.txt').write(content)</lang>
new File('output.txt').write(content)</syntaxhighlight>


Using Ant
Using Ant
<lang groovy>new AntBuilder().copy(file:'input.txt', toFile:'output.txt', overwrite:true)</lang>
<syntaxhighlight lang="groovy">new AntBuilder().copy(file:'input.txt', toFile:'output.txt', overwrite:true)</syntaxhighlight>


Buffered
Buffered
<lang groovy>new File('output.txt').withWriter( w ->
<syntaxhighlight lang="groovy">new File('output.txt').withWriter( w ->
new File('input.txt').withReader( r -> w << r }
new File('input.txt').withReader( r -> w << r }
}</lang>
}</syntaxhighlight>


=={{header|GUISS}}==
=={{header|GUISS}}==


<lang guiss>Start,My Documents,Rightclick:input.txt,Copy,Menu,Edit,Paste,
<syntaxhighlight lang="guiss">Start,My Documents,Rightclick:input.txt,Copy,Menu,Edit,Paste,
Rightclick:Copy of input.txt,Rename,Type:output.txt[enter]</lang>
Rightclick:Copy of input.txt,Rename,Type:output.txt[enter]</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
Note: this doesn't keep the file in memory. Buffering is provided by lazy evaluation.
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>
<syntaxhighlight lang="haskell">main = readFile "input.txt" >>= writeFile "output.txt"</syntaxhighlight>


=={{header|hexiscript}}==
=={{header|hexiscript}}==
<lang hexiscript>let in openin "input.txt"
<syntaxhighlight lang="hexiscript">let in openin "input.txt"
let out openout "output.txt"
let out openout "output.txt"
while !(catch (let c read char in))
while !(catch (let c read char in))
write c out
write c out
endwhile
endwhile
close in; close out</lang>
close in; close out</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
Copy via system call:
Copy via system call:
<lang hicest>CHARACTER input='input.txt ', output='output.txt ', c, buffer*4096
<syntaxhighlight 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>
SYSTEM(COPY=input//output, ERror=11) ! on error branch to label 11 (not shown)</syntaxhighlight>
Read and write line by line
Read and write line by line
<lang hicest>OPEN(FIle=input, OLD, ERror=21) ! on error branch to label 21 (not shown)
<syntaxhighlight lang="hicest">OPEN(FIle=input, OLD, ERror=21) ! on error branch to label 21 (not shown)
OPEN(FIle=output)
OPEN(FIle=output)
DO i = 1, 1E300 ! "infinite" loop, exited on end-of-file error
DO i = 1, 1E300 ! "infinite" loop, exited on end-of-file error
Line 2,070: Line 2,070:
WRITE(FIle=output, ERror=23) buffer ! on error branch to label 23 (not shown)
WRITE(FIle=output, ERror=23) buffer ! on error branch to label 23 (not shown)
ENDDO
ENDDO
22 WRITE(FIle=output, CLoSe=1)</lang>
22 WRITE(FIle=output, CLoSe=1)</syntaxhighlight>
Read and write in 1 block
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)
<syntaxhighlight 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)
OPEN(FIle=output, SEQuential, UNFormatted, ERror=32) ! on error branch to label 32 (not shown)
ALLOCATE(c, len)
ALLOCATE(c, len)
READ(FIle=input, CLoSe=1) c
READ(FIle=input, CLoSe=1) c
WRITE(FIle=output, CLoSe=1) c END</lang>
WRITE(FIle=output, CLoSe=1) c END</syntaxhighlight>


=={{header|i}}==
=={{header|i}}==
<lang i>software {
<syntaxhighlight lang="i">software {
file = load("input.txt")
file = load("input.txt")
open("output.txt").write(file)
open("output.txt").write(file)
} </lang>
} </syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{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().
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()
<syntaxhighlight lang="icon">procedure main()
in := open(f := "input.txt","r") | stop("Unable to open ",f)
in := open(f := "input.txt","r") | stop("Unable to open ",f)
out := open(f := "output.txt","w") | stop("Unable to open ",f)
out := open(f := "output.txt","w") | stop("Unable to open ",f)
while write(out,read(in))
while write(out,read(in))
end</lang>
end</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==


<lang idl>; open two LUNs
<syntaxhighlight lang="idl">; open two LUNs
openw,unit1,'output.txt,/get
openw,unit1,'output.txt,/get
openr,unit2,'input.txt',/get
openr,unit2,'input.txt',/get
Line 2,105: Line 2,105:
writeu,unit1,buff
writeu,unit1,buff
; that's all
; that's all
close,/all</lang>
close,/all</syntaxhighlight>


=={{header|Io}}==
=={{header|Io}}==


<lang io>inf := File with("input.txt") openForReading
<syntaxhighlight lang="io">inf := File with("input.txt") openForReading
outf := File with("output.txt") openForUpdating
outf := File with("output.txt") openForUpdating


Line 2,118: Line 2,118:
inf close
inf close
outf close
outf close
</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==


<lang j> 'output.txt' (1!:2~ 1!:1)&< 'input.txt'</lang>
<syntaxhighlight lang="j"> 'output.txt' (1!:2~ 1!:1)&< 'input.txt'</syntaxhighlight>


Or using the system library <tt>files</tt>:
Or using the system library <tt>files</tt>:


<lang j>require 'files'
<syntaxhighlight lang="j">require 'files'
'output.txt' (fwrite~ fread) 'input.txt'</lang>
'output.txt' (fwrite~ fread) 'input.txt'</syntaxhighlight>


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.)
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,136: Line 2,136:
Simple version; Files ''may'' be closed automatically by OS, on some systems.
Simple version; Files ''may'' be closed automatically by OS, on some systems.


<lang java>import java.io.*;
<syntaxhighlight lang="java">import java.io.*;


public class FileIODemo {
public class FileIODemo {
Line 2,153: Line 2,153:
}
}
}
}
}</lang>
}</syntaxhighlight>


This version closes both files after without OS intervention.
This version closes both files after without OS intervention.


<lang java>import java.io.*;
<syntaxhighlight lang="java">import java.io.*;


public class FileIODemo2 {
public class FileIODemo2 {
Line 2,186: Line 2,186:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{works with|Java|1.4}}
{{works with|Java|1.4}}
'''Package''' [[nio]]
'''Package''' [[nio]]


<lang java>import java.io.*;
<syntaxhighlight lang="java">import java.io.*;
import java.nio.channels.*;
import java.nio.channels.*;


Line 2,216: Line 2,216:
}
}
}
}
}</lang>
}</syntaxhighlight>


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.
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.*;
<syntaxhighlight lang="java">import java.io.*;
public class Test {
public class Test {
public static void main (String[] args) throws IOException {
public static void main (String[] args) throws IOException {
Line 2,233: Line 2,233:
bw.close();
bw.close();
}
}
}</lang>
}</syntaxhighlight>
{{works with|Java|7+}}
{{works with|Java|7+}}
<lang java5>import java.nio.file.*;
<syntaxhighlight lang="java5">import java.nio.file.*;
public class Copy{
public class Copy{
public static void main(String[] args) throws Exception{
public static void main(String[] args) throws Exception{
Line 2,243: Line 2,243:
Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);
Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{works with|JScript}}
{{works with|JScript}}
<lang javascript>var fso = new ActiveXObject("Scripting.FileSystemObject");
<syntaxhighlight lang="javascript">var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2;
var ForReading = 1, ForWriting = 2;
var f_in = fso.OpenTextFile('input.txt', ForReading);
var f_in = fso.OpenTextFile('input.txt', ForReading);
Line 2,261: Line 2,261:


f_in.Close();
f_in.Close();
f_out.Close();</lang>
f_out.Close();</syntaxhighlight>


{{works with|Node.js}}
{{works with|Node.js}}
<lang javascript>
<syntaxhighlight lang="javascript">
var fs = require('fs');
var fs = require('fs');
require('util').pump(fs.createReadStream('input.txt', {flags:'r'}), fs.createWriteStream('output.txt', {flags:'w+'}));
require('util').pump(fs.createReadStream('input.txt', {flags:'r'}), fs.createWriteStream('output.txt', {flags:'w+'}));
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
If the input file consists of ordinary lines of text, then the lines can be copied verbatim, one by one, as follows:
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
<syntaxhighlight 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
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: `.`
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: `.`
Line 2,284: Line 2,284:
=={{header|Julia}}==
=={{header|Julia}}==
Here we read the content of file1 into the variable mystring. Then we write the content of string to file2.
Here we read the content of file1 into the variable mystring. Then we write the content of string to file2.
<lang Julia>mystring = read("file1", String)
<syntaxhighlight lang="julia">mystring = read("file1", String)
open(io->write(io, mystring), "file2", "w")</lang>
open(io->write(io, mystring), "file2", "w")</syntaxhighlight>
Note however that Julia has a `cp` function to copy the content of a file to another file.
Note however that Julia has a `cp` function to copy the content of a file to another file.
<lang julia>cp("file1","file2")</lang>
<syntaxhighlight lang="julia">cp("file1","file2")</syntaxhighlight>
We can also open and close the file handles manually.
We can also open and close the file handles manually.
<lang Julia>infile = open("file1", "r")
<syntaxhighlight lang="julia">infile = open("file1", "r")
outfile = open("file2", "w")
outfile = open("file2", "w")
write(outfile, read(infile, String))
write(outfile, read(infile, String))
close(outfile)
close(outfile)
close(infile)</lang>
close(infile)</syntaxhighlight>
Here is a one-liner that guarantees that the file handle is closed
Here is a one-liner that guarantees that the file handle is closed
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, read("file1", String)), "file2", "w")</lang>
<syntaxhighlight lang="julia">open(IO ->write(IO, read("file1", String)), "file2", "w")</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
<lang K>`output.txt 0:0:`input.txt</lang>
<syntaxhighlight lang="k">`output.txt 0:0:`input.txt</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==


<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


import java.io.File
import java.io.File
Line 2,310: Line 2,310:
val text = File("input.txt").readText()
val text = File("input.txt").readText()
File("output.txt").writeText(text)
File("output.txt").writeText(text)
}</lang>
}</syntaxhighlight>


=={{header|LabVIEW}}==
=={{header|LabVIEW}}==
Line 2,317: Line 2,317:


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>: puts(*) . "\n" . ;
<syntaxhighlight lang="lang5">: puts(*) . "\n" . ;
: set-file '> swap open ;
: set-file '> swap open ;
: >>contents slurp puts ;
: >>contents slurp puts ;
Line 2,323: Line 2,323:
swap set-file 'fdst set fdst fout >>contents fdst close ;
swap set-file 'fdst set fdst fout >>contents fdst close ;


'output.txt 'input.txt copy-file</lang>
'output.txt 'input.txt copy-file</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>nomainwin
<syntaxhighlight lang="lb">nomainwin


open "input.txt" for input as #f1
open "input.txt" for input as #f1
Line 2,337: Line 2,337:
close #f2
close #f2


end</lang>
end</syntaxhighlight>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>----------------------------------------
<syntaxhighlight lang="lingo">----------------------------------------
-- Returns file as ByteArray
-- Returns file as ByteArray
-- @param {string} tFile
-- @param {string} tFile
Line 2,373: Line 2,373:
fp.closeFile()
fp.closeFile()
return true
return true
end</lang>
end</syntaxhighlight>


<lang lingo>data = getBytes("input.txt")
<syntaxhighlight lang="lingo">data = getBytes("input.txt")
putBytes("output.txt", data)</lang>
putBytes("output.txt", data)</syntaxhighlight>


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>Section Header
<syntaxhighlight lang="lisaac">Section Header


+ name := FILE_IO;
+ name := FILE_IO;
Line 2,410: Line 2,410:
};
};
};
};
);</lang>
);</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
{{works with|UCB Logo}}
{{works with|UCB Logo}}
<lang logo>to copy :from :to
<syntaxhighlight lang="logo">to copy :from :to
openread :from
openread :from
openwrite :to
openwrite :to
Line 2,423: Line 2,423:
end
end


copy "input.txt "output.txt</lang>
copy "input.txt "output.txt</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>
<syntaxhighlight lang="lua">
inFile = io.open("input.txt", "r")
inFile = io.open("input.txt", "r")
data = inFile:read("*all") -- may be abbreviated to "*a";
data = inFile:read("*all") -- may be abbreviated to "*a";
Line 2,439: Line 2,439:
-- Oneliner version:
-- Oneliner version:
io.open("output.txt", "w"):write(io.open("input.txt", "r"):read("*a"))
io.open("output.txt", "w"):write(io.open("input.txt", "r"):read("*a"))
</syntaxhighlight>
</lang>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 2,454: Line 2,454:
We can edit thousands of lines. Document is a double linked list.
We can edit thousands of lines. Document is a double linked list.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module FileInputOutput {
Module FileInputOutput {
Edit "Input.txt"
Edit "Input.txt"
Line 2,465: Line 2,465:
}
}
FileInputOutput
FileInputOutput
</syntaxhighlight>
</lang>
===Using Buffer Object===
===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).
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 {
Module Using_Buffer {
M=buffer("Input.txt")
M=buffer("Input.txt")
Line 2,486: Line 2,486:
}
}
Using_Buffer
Using_Buffer
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
inout:=proc(filename)
inout:=proc(filename)
local f;
local f;
Line 2,495: Line 2,495:
FileTools[Text][WriteFile]("output.txt",f);
FileTools[Text][WriteFile]("output.txt",f);
end proc;
end proc;
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>SetDirectory@NotebookDirectory[];
<syntaxhighlight lang="mathematica">SetDirectory@NotebookDirectory[];
If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ];
If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ];
CopyFile["input.txt", "output.txt"]</lang>
CopyFile["input.txt", "output.txt"]</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>inFile = openFile "input.txt"
<syntaxhighlight lang="maxscript">inFile = openFile "input.txt"
outFile = createFile "output.txt"
outFile = createFile "output.txt"
while not EOF inFile do
while not EOF inFile do
Line 2,510: Line 2,510:
)
)
close inFile
close inFile
close outFile</lang>
close outFile</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang mercury>:- module file_io.
<syntaxhighlight lang="mercury">:- module file_io.
:- interface.
:- interface.


Line 2,552: Line 2,552:
io.stderr_stream(Stderr, !IO),
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, io.error_message(Error), !IO),
io.write_string(Stderr, io.error_message(Error), !IO),
io.set_exit_status(1, !IO).</lang>
io.set_exit_status(1, !IO).</syntaxhighlight>


=={{header|mIRC Scripting Language}}==
=={{header|mIRC Scripting Language}}==


{{works with|mIRC}}
{{works with|mIRC}}
<lang mirc>alias Write2FileAndReadIt {
<syntaxhighlight lang="mirc">alias Write2FileAndReadIt {
.write myfilename.txt Goodbye Mike!
.write myfilename.txt Goodbye Mike!
.echo -a Myfilename.txt contains: $read(myfilename.txt,1)
.echo -a Myfilename.txt contains: $read(myfilename.txt,1)
}</lang>
}</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE FileIO EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE FileIO EXPORTS Main;


IMPORT IO, Rd, Wr;
IMPORT IO, Rd, Wr;
Line 2,581: Line 2,581:
Rd.Close(infile);
Rd.Close(infile);
Wr.Close(outfile);
Wr.Close(outfile);
END FileIO.</lang>
END FileIO.</syntaxhighlight>


The code <code><*FATAL ANY*></code> is a pragma that tells the program to die if any exceptions (such as read/write errors) occur.
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,587: Line 2,587:
=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Ursa}}
{{trans|Ursa}}
<lang nanoquery>import Nanoquery.IO
<syntaxhighlight lang="nanoquery">import Nanoquery.IO
input = new(File, "input.txt")
input = new(File, "input.txt")
Line 2,596: Line 2,596:
contents = input.readAll()
contents = input.readAll()
output.write(contents)</lang>
output.write(contents)</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{works with|Java|7}}
{{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.
Takes advantage of some of the new path and file handling features of [[Java|Java's]] <tt>java.nio</tt> library.
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,628: Line 2,628:


return
return
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
Copying the file directly (without buffer):
Copying the file directly (without buffer):
<lang nim>import os
<syntaxhighlight lang="nim">import os
copyfile("input.txt", "output.txt")</lang>
copyfile("input.txt", "output.txt")</syntaxhighlight>


Buffer for the entire file:
Buffer for the entire file:
<lang nim>let x = readFile("input.txt")
<syntaxhighlight lang="nim">let x = readFile("input.txt")
writeFile("output.txt", x)</lang>
writeFile("output.txt", x)</syntaxhighlight>


Line by line:
Line by line:
<lang nim>var
<syntaxhighlight lang="nim">var
i = open("input.txt")
i = open("input.txt")
o = open("output.txt", fmWrite)
o = open("output.txt", fmWrite)
Line 2,648: Line 2,648:


i.close()
i.close()
o.close()</lang>
o.close()</syntaxhighlight>


With a fixed sized buffer:
With a fixed sized buffer:
<lang nim>const size = 4096
<syntaxhighlight lang="nim">const size = 4096


var
var
Line 2,662: Line 2,662:


i.close()
i.close()
o.close()</lang>
o.close()</syntaxhighlight>


Using memory mapping:
Using memory mapping:
<lang nim>import memfiles
<syntaxhighlight lang="nim">import memfiles


var
var
Line 2,675: Line 2,675:


i.close()
i.close()
o.close()</lang>
o.close()</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>use IO;
<syntaxhighlight lang="objeck">use IO;


bundle Default {
bundle Default {
Line 2,697: Line 2,697:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Object Pascal}}==
=={{header|Object Pascal}}==
Line 2,704: Line 2,704:
For a more object oriented style one can use a TFilestream:
For a more object oriented style one can use a TFilestream:


<lang pascal>uses
<syntaxhighlight lang="pascal">uses
classes;
classes;
begin
begin
Line 2,713: Line 2,713:
Free;
Free;
end;
end;
end;</lang>
end;</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
Line 2,719: Line 2,719:
For copying files, using <code>NSFileManager</code> is preferred:
For copying files, using <code>NSFileManager</code> is preferred:


<lang objc>[[NSFileManager defaultManager] copyItemAtPath:@"input.txt" toPath:@"output.txt" error:NULL];</lang>
<syntaxhighlight lang="objc">[[NSFileManager defaultManager] copyItemAtPath:@"input.txt" toPath:@"output.txt" error:NULL];</syntaxhighlight>


If you want to do it manually:
If you want to do it manually:


<lang objc>NSData *data = [NSData dataWithContentsOfFile:@"input.txt"];
<syntaxhighlight lang="objc">NSData *data = [NSData dataWithContentsOfFile:@"input.txt"];


[data writeToFile:@"output.txt" atomically:YES];</lang>
[data writeToFile:@"output.txt" atomically:YES];</syntaxhighlight>


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 :-)
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,733: Line 2,733:
=={{header|OCaml}}==
=={{header|OCaml}}==
By line:
By line:
<lang ocaml>let () =
<syntaxhighlight lang="ocaml">let () =
let ic = open_in "input.txt" in
let ic = open_in "input.txt" in
let oc = open_out "output.txt" in
let oc = open_out "output.txt" in
Line 2,745: Line 2,745:
close_in ic;
close_in ic;
close_out oc;
close_out oc;
;;</lang>
;;</syntaxhighlight>


By character:
By character:
<lang ocaml>let () =
<syntaxhighlight lang="ocaml">let () =
let ic = open_in "input.txt" in
let ic = open_in "input.txt" in
let oc = open_out "output.txt" in
let oc = open_out "output.txt" in
Line 2,759: Line 2,759:
close_in ic;
close_in ic;
close_out oc;
close_out oc;
;;</lang>
;;</syntaxhighlight>


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


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>
<syntaxhighlight lang="octave">
in = fopen("input.txt", "r", "native");
in = fopen("input.txt", "r", "native");
out = fopen("output.txt", "w","native");
out = fopen("output.txt", "w","native");
Line 2,792: Line 2,792:
fclose(out);
fclose(out);
end
end
</syntaxhighlight>
</lang>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: fcopy(in, out)
<syntaxhighlight lang="oforth">: fcopy(in, out)
| f g |
| f g |
File newMode(in, File.BINARY) dup open(File.READ) ->f
File newMode(in, File.BINARY) dup open(File.READ) ->f
Line 2,802: Line 2,802:
while(f >> dup notNull) [ g addChar ] drop
while(f >> dup notNull) [ g addChar ] drop
f close g close ;</lang>
f close g close ;</syntaxhighlight>


Usage :
Usage :
<lang Oforth>fcopy("input.txt", "output.txt")</lang>
<syntaxhighlight lang="oforth">fcopy("input.txt", "output.txt")</syntaxhighlight>


=={{header|OpenEdge/Progress}}==
=={{header|OpenEdge/Progress}}==
<lang Progress (OpenEdge ABL)>COPY-LOB FROM FILE "input.txt" TO FILE "output.txt".</lang>
<syntaxhighlight lang="progress (openedge abl)">COPY-LOB FROM FILE "input.txt" TO FILE "output.txt".</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
class TextFile from Open.file Open.text end
class TextFile from Open.file Open.text end


Line 2,827: Line 2,827:
{CopyAll In Out}
{CopyAll In Out}
{Out close}
{Out close}
{In close}</lang>
{In close}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>f=read("filename.in");
<syntaxhighlight lang="parigp">f=read("filename.in");
write("filename.out", f);</lang>
write("filename.out", f);</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 2,840: Line 2,840:


{{works with|Perl|5.8.8}}
{{works with|Perl|5.8.8}}
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl


open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!";
open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!";
Line 2,857: Line 2,857:


close $fh_in;
close $fh_in;
close $fh_out;</lang>
close $fh_out;</syntaxhighlight>


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 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,864: Line 2,864:
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
whole file as a single string (safe on small binary files)
whole file as a single string (safe on small binary files)
<!--<lang Phix>-->
<!--<syntaxhighlight lang="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;">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>
<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,871: Line 2,871:
<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;">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;">)
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">fn<span style="color: #0000FF;">)
<!--</lang>-->
<!--</syntaxhighlight>-->
line-by-line (text files only)
line-by-line (text files only)
<!--<lang Phix>-->
<!--<syntaxhighlight lang="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: #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>
<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,884: Line 2,884:
<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;">infn<span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">outfn<span style="color: #0000FF;">)
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">outfn<span style="color: #0000FF;">)
<!--</lang>-->
<!--</syntaxhighlight>-->
byte-by-byte (safe on binary files)
byte-by-byte (safe on binary files)
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">integer</span> <span style="color: #004080;">byte<span style="color: #0000FF;">,</span>
<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>
<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,897: Line 2,897:
<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;">infd<span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">outfd<span style="color: #0000FF;">)
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">outfd<span style="color: #0000FF;">)
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==


{{works with|PHP|4}}
{{works with|PHP|4}}
<lang php><?php
<syntaxhighlight lang="php"><?php


if (!$in = fopen('input.txt', 'r')) {
if (!$in = fopen('input.txt', 'r')) {
Line 2,919: Line 2,919:
fclose($out);
fclose($out);
fclose($in);
fclose($in);
?></lang>
?></syntaxhighlight>
{{works with|PHP|5}}
{{works with|PHP|5}}
<lang php><?php
<syntaxhighlight lang="php"><?php
if ($contents = file_get_contents('input.txt')) {
if ($contents = file_get_contents('input.txt')) {
if (!file_put_contents('output.txt', $contents)) {
if (!file_put_contents('output.txt', $contents)) {
Line 2,930: Line 2,930:
echo('Could not open input file.');
echo('Could not open input file.');
}
}
?></lang>
?></syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
===Using a variable===
===Using a variable===
<lang PicoLisp>(let V (in "input.txt" (till))
<syntaxhighlight lang="picolisp">(let V (in "input.txt" (till))
(out "output.txt" (prin V)) )</lang>
(out "output.txt" (prin V)) )</syntaxhighlight>
===Skipping intermediate variable===
===Skipping intermediate variable===
<lang PicoLisp>(in "input.txt"
<syntaxhighlight lang="picolisp">(in "input.txt"
(out "output.txt"
(out "output.txt"
(echo) ) )</lang>
(echo) ) )</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
===Line by line===
===Line by line===
<syntaxhighlight lang="pike">
<lang Pike>
object lines = Stdio.File("input.txt")->line_iterator();
object lines = Stdio.File("input.txt")->line_iterator();
object out = Stdio.File("output.txt", "cw");
object out = Stdio.File("output.txt", "cw");
foreach(lines; int line_number; string line)
foreach(lines; int line_number; string line)
out->write(line + "\n");
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.
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}}==
=={{header|PL/I}}==
<lang pli>
<syntaxhighlight lang="pli">
declare in file, out file;
declare in file, out file;


Line 2,961: Line 2,961:
put file (out) edit (line) (A);
put file (out) edit (line) (A);
end;
end;
</syntaxhighlight>
</lang>


=={{header|Pop11}}==
=={{header|Pop11}}==
Line 2,967: Line 2,967:
Char by char copy:
Char by char copy:


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


Low level block copy:
Low level block copy:


<lang pop11>lvars i_file = sysopen('input.txt', 0, true);
<syntaxhighlight lang="pop11">lvars i_file = sysopen('input.txt', 0, true);
lvars o_file = syscreate('output.txt', 1, true);
lvars o_file = syscreate('output.txt', 1, true);
lvars buff = inits(4096);
lvars buff = inits(4096);
Line 2,982: Line 2,982:
while (sysread(i_file, buff, length(buff)) ->> i) > 0 do
while (sysread(i_file, buff, length(buff)) ->> i) > 0 do
syswrite(o_file, buff, i);
syswrite(o_file, buff, i);
endwhile;</lang>
endwhile;</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Line 2,988: Line 2,988:
Read the input file then pipe it's contents to output file.
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.
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>
<syntaxhighlight lang="powershell">Get-Content $PWD\input.txt | Out-File $PWD\output.txt</syntaxhighlight>


Using an alternate cmdlet to write the file
Using an alternate cmdlet to write the file
<lang PowerShell>Get-Content $PWD\input.txt | Set-Content $PWD\output.txt</lang>
<syntaxhighlight lang="powershell">Get-Content $PWD\input.txt | Set-Content $PWD\output.txt</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
Line 2,997: Line 2,997:


Basic file copy
Basic file copy
<lang PureBasic>CopyFile("input.txt","output.txt")</lang>
<syntaxhighlight lang="purebasic">CopyFile("input.txt","output.txt")</syntaxhighlight>




Line by line
Line by line
<lang PureBasic>in = ReadFile(#PB_Any,"input.txt")
<syntaxhighlight lang="purebasic">in = ReadFile(#PB_Any,"input.txt")
If in
If in
out = CreateFile(#PB_Any,"output.txt")
out = CreateFile(#PB_Any,"output.txt")
Line 3,013: Line 3,013:
EndIf
EndIf
CloseFile(in)
CloseFile(in)
EndIf</lang>
EndIf</syntaxhighlight>




Reading & writing the complete file in one pass
Reading & writing the complete file in one pass
<lang PureBasic>If ReadFile(0,"input.txt")
<syntaxhighlight lang="purebasic">If ReadFile(0,"input.txt")
Define MyLine$, *Buffer, length
Define MyLine$, *Buffer, length
length=FileSize("input.txt")
length=FileSize("input.txt")
Line 3,030: Line 3,030:
EndIf
EndIf
CloseFile(0)
CloseFile(0)
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Line 3,037: Line 3,037:
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).
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
<syntaxhighlight lang="python">import shutil
shutil.copyfile('input.txt', 'output.txt')</lang>
shutil.copyfile('input.txt', 'output.txt')</syntaxhighlight>


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


<lang python>infile = open('input.txt', 'r')
<syntaxhighlight lang="python">infile = open('input.txt', 'r')
outfile = open('output.txt', 'w')
outfile = open('output.txt', 'w')
for line in infile:
for line in infile:
outfile.write(line)
outfile.write(line)
outfile.close()
outfile.close()
infile.close()</lang>
infile.close()</syntaxhighlight>


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


<lang python>import sys
<syntaxhighlight lang="python">import sys
try:
try:
infile = open('input.txt', 'r')
infile = open('input.txt', 'r')
Line 3,070: Line 3,070:
finally:
finally:
infile.close()
infile.close()
outfile.close()</lang>
outfile.close()</syntaxhighlight>


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


<lang python>import sys
<syntaxhighlight lang="python">import sys
try:
try:
with open('input.txt') as infile:
with open('input.txt') as infile:
Line 3,082: Line 3,082:
except IOError:
except IOError:
print >> sys.stderr, "Some I/O Error occurred"
print >> sys.stderr, "Some I/O Error occurred"
sys.exit(1)</lang>
sys.exit(1)</syntaxhighlight>


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.
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.
Line 3,092: Line 3,092:
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>.
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>.


<lang Quackery> $ "input.txt" sharefile drop
<syntaxhighlight lang="quackery"> $ "input.txt" sharefile drop
temp put
temp put
temp share
temp share
$ "output.txt" putfile drop
$ "output.txt" putfile drop
</syntaxhighlight>
</lang>


=={{header|R}}==
=={{header|R}}==
If files are textual we can use <tt>readLines</tt> ("-1" means "read until the end")
If files are textual we can use <tt>readLines</tt> ("-1" means "read until the end")


<lang rsplus>src <- file("input.txt", "r")
<syntaxhighlight lang="rsplus">src <- file("input.txt", "r")
dest <- file("output.txt", "w")
dest <- file("output.txt", "w")


fc <- readLines(src, -1)
fc <- readLines(src, -1)
writeLines(fc, dest)
writeLines(fc, dest)
close(src); close(dest)</lang>
close(src); close(dest)</syntaxhighlight>


If the files are not textual but "generic":
If the files are not textual but "generic":


<lang rsplus>src <- file("input.txt", "rb")
<syntaxhighlight lang="rsplus">src <- file("input.txt", "rb")
dest <- file("output.txt", "wb")
dest <- file("output.txt", "wb")


Line 3,116: Line 3,116:
writeBin(v, dest)
writeBin(v, dest)
}
}
close(src); close(dest)</lang>
close(src); close(dest)</syntaxhighlight>


Another simpler way is to use <tt>file.copy</tt>
Another simpler way is to use <tt>file.copy</tt>


<lang rsplus>file.copy("input.txt", "output.txt", overwrite = FALSE)</lang>
<syntaxhighlight lang="rsplus">file.copy("input.txt", "output.txt", overwrite = FALSE)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(define file-content
(define file-content
(with-input-from-file "input.txt"
(with-input-from-file "input.txt"
Line 3,135: Line 3,135:
(with-output-to-file "output.txt"
(with-output-to-file "output.txt"
(lambda ()
(lambda ()
(write file-content)))</lang>
(write file-content)))</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
Line 3,143: Line 3,143:


{{works with|Rakudo|2016.07}}
{{works with|Rakudo|2016.07}}
<lang perl6>spurt "output.txt", slurp "input.txt";</lang>
<syntaxhighlight lang="raku" line>spurt "output.txt", slurp "input.txt";</syntaxhighlight>


Otherwise, copying line-by line:
Otherwise, copying line-by line:


{{works with|Rakudo|2015.12}}
{{works with|Rakudo|2015.12}}
<lang perl6>my $in = open "input.txt";
<syntaxhighlight lang="raku" line>my $in = open "input.txt";
my $out = open "output.txt", :w;
my $out = open "output.txt", :w;
for $in.lines -> $line {
for $in.lines -> $line {
Line 3,154: Line 3,154:
}
}
$in.close;
$in.close;
$out.close;</lang>
$out.close;</syntaxhighlight>


=={{header|RapidQ}}==
=={{header|RapidQ}}==
Line 3,162: Line 3,162:
The first version copies text line by line, as in the ''BASIC'' example.
The first version copies text line by line, as in the ''BASIC'' example.


<lang rapidq>$INCLUDE "rapidq.inc"
<syntaxhighlight lang="rapidq">$INCLUDE "rapidq.inc"


DIM File1 AS QFileStream
DIM File1 AS QFileStream
Line 3,176: Line 3,176:


File1.Close
File1.Close
File2.Close</lang>
File2.Close</syntaxhighlight>


When just copying data, the code can be simplified by using the CopyFrom method.<br />
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.)
(The second parameter for CopyFrom is number of bytes to copy, 0 = copy the whole file.)


<lang rapidq>$INCLUDE "rapidq.inc"
<syntaxhighlight lang="rapidq">$INCLUDE "rapidq.inc"


DIM File1 AS QFileStream
DIM File1 AS QFileStream
Line 3,192: Line 3,192:


File1.Close
File1.Close
File2.Close</lang>
File2.Close</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==
<lang raven>'input.txt' read 'output.txt' write</lang>
<syntaxhighlight lang="raven">'input.txt' read 'output.txt' write</syntaxhighlight>


=={{header|REALbasic}}==
=={{header|REALbasic}}==
<syntaxhighlight lang="vb">
<lang vb>
Sub WriteToFile(input As FolderItem, output As FolderItem)
Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream
Dim tis As TextInputStream
Line 3,210: Line 3,210:
tos.Close
tos.Close
End Sub
End Sub
</syntaxhighlight>
</lang>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>write %output.txt read %input.txt
<syntaxhighlight lang="rebol">write %output.txt read %input.txt


; No line translations:
; No line translations:
Line 3,220: Line 3,220:
; Save a web page:
; Save a web page:
write/binary %output.html read http://rosettacode.org
write/binary %output.html read http://rosettacode.org
</syntaxhighlight>
</lang>


=={{header|Red}}==
=={{header|Red}}==
<syntaxhighlight lang="red">
<lang Red>
file: read %input.txt
file: read %input.txt
write %output.txt file</lang>
write %output.txt file</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>with files'
<syntaxhighlight lang="retro">with files'
here dup "input.txt" slurp "output.txt" spew</lang>
here dup "input.txt" slurp "output.txt" spew</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 3,240: Line 3,240:
The two &nbsp; ''best programming practice'' &nbsp; REXX statements are only needed if there is another calling program in the invocation chain
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.
<br>(which may want to (re-)use the two files just used.
<lang rexx>/*REXX program reads a file and copies the contents into an output file (on a line by line basis).*/
<syntaxhighlight 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. */
iFID = 'input.txt' /*the name of the input file. */
oFID = 'output.txt' /* " " " " output " */
oFID = 'output.txt' /* " " " " output " */
Line 3,251: Line 3,251:


call lineout iFID /*close input file, just to be safe.*/ /* ◄■■■■■■ best programming practice.*/
call lineout iFID /*close input file, just to be safe.*/ /* ◄■■■■■■ best programming practice.*/
call lineout oFID /* " output " " " " " */ /* ◄■■■■■■ best programming practice.*/</lang>
call lineout oFID /* " output " " " " " */ /* ◄■■■■■■ best programming practice.*/</syntaxhighlight>


===version 2===
===version 2===
Note that this version is limited to files less than one million bytes (and/or possibly virtual memory).
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*****
<syntaxhighlight 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)
* 03.09.2012 Walter Pachl (without erase string would be appended)
**********************************************************************/
**********************************************************************/
Line 3,262: Line 3,262:
'erase' ofid /* avoid appending */
'erase' ofid /* avoid appending */
s=charin(ifid,,1000000) /* read the input file */
s=charin(ifid,,1000000) /* read the input file */
Call charout ofid,s /* write to output file */</lang>
Call charout ofid,s /* write to output file */</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
fn1 = "ReadMe.txt"
fn1 = "ReadMe.txt"
fn2 = "ReadMe2.txt"
fn2 = "ReadMe2.txt"
Line 3,285: Line 3,285:
fseek(fp,0,c_filestart)
fseek(fp,0,c_filestart)
return nfilesize
return nfilesize
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
In general, open both files in binary mode.
In general, open both files in binary mode.


<lang ruby>str = File.open('input.txt', 'rb') {|f| f.read}
<syntaxhighlight lang="ruby">str = File.open('input.txt', 'rb') {|f| f.read}
File.open('output.txt', 'wb') {|f| f.write str}</lang>
File.open('output.txt', 'wb') {|f| f.write str}</syntaxhighlight>


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


<lang ruby># Only if 'input.txt' is a text file!
<syntaxhighlight lang="ruby"># Only if 'input.txt' is a text file!
# Only if pipe '|' is not first character of path!
# Only if pipe '|' is not first character of path!
str = IO.read('input.txt')
str = IO.read('input.txt')
open('output.txt', 'w') {|f| f.write str}</lang>
open('output.txt', 'w') {|f| f.write str}</syntaxhighlight>


To copy a file block by block, use FileUtils from the standard library.
To copy a file block by block, use FileUtils from the standard library.


<lang ruby>require 'fileutils'
<syntaxhighlight lang="ruby">require 'fileutils'
FileUtils.copy_file 'input.txt', 'output.txt'</lang>
FileUtils.copy_file 'input.txt', 'output.txt'</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run 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
fileLen = LOF(#in) 'Length Of File
fileData$ = input$(#in, fileLen) 'read entire file
fileData$ = input$(#in, fileLen) 'read entire file
Line 3,324: Line 3,324:
close #in
close #in
close #out
close #out
</syntaxhighlight>
</lang>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::fs::File;
<syntaxhighlight lang="rust">use std::fs::File;
use std::io::{Read, Write};
use std::io::{Read, Write};


Line 3,337: Line 3,337:
file.write_all(&data).unwrap();
file.write_all(&data).unwrap();
}
}
</syntaxhighlight>
</lang>
The above program will panic with any sort of error. The following shows proper error handling:
The above program will panic with any sort of error. The following shows proper error handling:
<lang rust>use std::fs::File;
<syntaxhighlight lang="rust">use std::fs::File;
use std::io::{self, Read, Write};
use std::io::{self, Read, Write};
use std::path::Path;
use std::path::Path;
Line 3,366: Line 3,366:
writeln!(&mut io::stderr(), "ERROR: {}", msg).expect("Could not write to stdout");
writeln!(&mut io::stderr(), "ERROR: {}", msg).expect("Could not write to stdout");
process::exit(code);
process::exit(code);
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
<lang scala>import java.io.{ FileNotFoundException, PrintWriter }
<syntaxhighlight lang="scala">import java.io.{ FileNotFoundException, PrintWriter }


object FileIO extends App {
object FileIO extends App {
Line 3,385: Line 3,385:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
Character by character copy<lang scheme>; Open ports for the input and output files
Character by character copy<syntaxhighlight lang="scheme">; Open ports for the input and output files
(define in-file (open-input-file "input.txt"))
(define in-file (open-input-file "input.txt"))
(define out-file (open-output-file "output.txt"))
(define out-file (open-output-file "output.txt"))
Line 3,401: Line 3,401:
(close-input-port in-file)
(close-input-port in-file)
(close-output-port out-file)
(close-output-port out-file)
</syntaxhighlight>
</lang>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 3,408: Line 3,408:
can be used to copy a source file to a destination.
can be used to copy a source file to a destination.


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "osfiles.s7i";
include "osfiles.s7i";


Line 3,414: Line 3,414:
begin
begin
copyFile("input.txt", "output.txt");
copyFile("input.txt", "output.txt");
end func;</lang>
end func;</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
Reading the file all at once:
Reading the file all at once:
<lang sensetalk>put file "input.txt" into fileContents
<syntaxhighlight lang="sensetalk">put file "input.txt" into fileContents
put fileContents into file "output.txt"</lang>
put fileContents into file "output.txt"</syntaxhighlight>
Reading the file line by line:
Reading the file line by line:
<lang sensetalk>put "input.txt" into inputFile
<syntaxhighlight lang="sensetalk">put "input.txt" into inputFile
put "output.txt" into outputFile
put "output.txt" into outputFile


Line 3,434: Line 3,434:


close file inputFile
close file inputFile
close file outputFile</lang>
close file outputFile</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var in = %f'input.txt'.open_r;
<syntaxhighlight lang="ruby">var in = %f'input.txt'.open_r;
var out = %f'output.txt'.open_w;
var out = %f'output.txt'.open_w;


in.each { |line|
in.each { |line|
out.print(line);
out.print(line);
};</lang>
};</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>(File newNamed: 'input.txt' &mode: File Read) sessionDo: [| :in |
<syntaxhighlight lang="slate">(File newNamed: 'input.txt' &mode: File Read) sessionDo: [| :in |
(File newNamed: 'output.txt' &mode: File CreateWrite) sessionDo: [| :out |
(File newNamed: 'output.txt' &mode: File CreateWrite) sessionDo: [| :out |
in >> out]]</lang>
in >> out]]</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>| in out |
<syntaxhighlight lang="smalltalk">| in out |
in := FileStream open: 'input.txt' mode: FileStream read.
in := FileStream open: 'input.txt' mode: FileStream read.
out := FileStream open: 'output.txt' mode: FileStream write.
out := FileStream open: 'output.txt' mode: FileStream write.
Line 3,456: Line 3,456:
whileFalse: [
whileFalse: [
out nextPut: (in next)
out nextPut: (in next)
]</lang>
]</syntaxhighlight>


=={{header|Snabel}}==
=={{header|Snabel}}==
Reads the entire file into into a list of buffers before writing and returns number of bytes written.
Reads the entire file into into a list of buffers before writing and returns number of bytes written.
<lang snabel>
<syntaxhighlight lang="snabel">
let: q Bin list;
let: q Bin list;
'input.txt' rfile read {{@q $1 push} when} for
'input.txt' rfile read {{@q $1 push} when} for
@q 'output.txt' rwfile write
@q 'output.txt' rwfile write
0 $1 &+ for
0 $1 &+ for
</syntaxhighlight>
</lang>


Alternative solution for large files with comparable performance to shell cp; also returns number of bytes written.
Alternative solution for large files with comparable performance to shell cp; also returns number of bytes written.
<lang snabel>
<syntaxhighlight lang="snabel">
let: q Bin list;
let: q Bin list;
let: wq @q fifo;
let: wq @q fifo;
Line 3,480: Line 3,480:
@q +? {@w &_ for} when
@q +? {@w &_ for} when
</syntaxhighlight>
</lang>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang snobol4>
<syntaxhighlight lang="snobol4">
input(.input,5,,'input.txt')
input(.input,5,,'input.txt')
output(.output,6,,'output.txt')
output(.output,6,,'output.txt')
while output = input :s(while)
while output = input :s(while)
end</lang>
end</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
{{works with|SML/NJ|110.59}}
{{works with|SML/NJ|110.59}}
<lang sml>fun copyFile (from, to) =
<syntaxhighlight lang="sml">fun copyFile (from, to) =
let
let
val instream = TextIO.openIn from
val instream = TextIO.openIn from
Line 3,500: Line 3,500:
in
in
true
true
end handle _ => false;</lang>
end handle _ => false;</syntaxhighlight>


=={{header|Stata}}==
=={{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.
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.
<lang stata>program copyfile
<syntaxhighlight lang="stata">program copyfile
file open fin using `1', read text
file open fin using `1', read text
file open fout using `2', write text replace
file open fout using `2', write text replace
Line 3,517: Line 3,517:
end
end


copyfile input.txt output.txt</lang>
copyfile input.txt output.txt</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 3,525: Line 3,525:
{{works with|tixwish}}
{{works with|tixwish}}
{{works with|tclkit}}
{{works with|tclkit}}
<lang tcl>set in [open "input.txt" r]
<syntaxhighlight lang="tcl">set in [open "input.txt" r]
set out [open "output.txt" w]
set out [open "output.txt" w]
# Obviously, arbitrary transformations could be added to the data at this point
# Obviously, arbitrary transformations could be added to the data at this point
puts -nonewline $out [read $in]
puts -nonewline $out [read $in]
close $in
close $in
close $out</lang>
close $out</syntaxhighlight>
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):
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):
<lang tcl>set in [open "input.txt" r]
<syntaxhighlight lang="tcl">set in [open "input.txt" r]
set out [open "output.txt" w]
set out [open "output.txt" w]
fcopy $in $out
fcopy $in $out
close $in
close $in
close $out</lang>
close $out</syntaxhighlight>
Or the minimal version if we don't need any processing of the data at all:
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>
<syntaxhighlight lang="tcl">file copy input.txt output.txt</syntaxhighlight>
===Other key file I/O operations===
===Other key file I/O operations===
;Writing a line to a file<nowiki>:</nowiki>
;Writing a line to a file<nowiki>:</nowiki>
<lang tcl>#open file for writing
<syntaxhighlight lang="tcl">#open file for writing
set myfile [open "README.TXT" w]
set myfile [open "README.TXT" w]
#write something to the file
#write something to the file
puts $myfile "This is line 1, so hello world...."
puts $myfile "This is line 1, so hello world...."
#close the file
#close the file
close $myfile</lang>
close $myfile</syntaxhighlight>
;Reading a line from a file<nowiki>:</nowiki>
;Reading a line from a file<nowiki>:</nowiki>
<lang tcl>#open file for reading
<syntaxhighlight lang="tcl">#open file for reading
set myfile [open "README.TXT" r]
set myfile [open "README.TXT" r]
#read something from the file
#read something from the file
Line 3,556: Line 3,556:
puts $mydata
puts $mydata
#close the file
#close the file
close $myfile</lang>
close $myfile</syntaxhighlight>


=={{header|Toka}}==
=={{header|Toka}}==
This is one method, which works with any type of file:
This is one method, which works with any type of file:


<lang toka>( source dest -- )
<syntaxhighlight lang="toka">( source dest -- )
{
{
value| source dest size buffer |
value| source dest size buffer |
Line 3,582: Line 3,582:
[ source file.close dest file.close ] is close-files
[ source file.close dest file.close ] is close-files
[ prepare [ read-source write-dest close-files ] ifTrue ]
[ prepare [ read-source write-dest close-files ] ifTrue ]
} is copy-file</lang>
} is copy-file</syntaxhighlight>


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


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


And a test:
And a test:


<lang toka>" input.txt" " output.txt" copy-file</lang>
<syntaxhighlight lang="toka">" input.txt" " output.txt" copy-file</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
ERROR/STOP CREATE ("input.txt", seq-o,-std-)
ERROR/STOP CREATE ("input.txt", seq-o,-std-)
Line 3,607: Line 3,607:
path2output=FULLNAME(TUSTEP,"output.txt",-std-)
path2output=FULLNAME(TUSTEP,"output.txt",-std-)
status=WRITE(path2output,contentinput)
status=WRITE(path2output,contentinput)
</syntaxhighlight>
</lang>


=={{header|TXR}}==
=={{header|TXR}}==
Line 3,613: Line 3,613:
As a character string:
As a character string:


<lang txrlisp>(let ((var (file-get-string "input.txt")))
<syntaxhighlight lang="txrlisp">(let ((var (file-get-string "input.txt")))
(file-put-string "output.txt" var))</lang>
(file-put-string "output.txt" var))</syntaxhighlight>


As a list of lines:
As a list of lines:


<lang txrlisp>(let ((var (file-get-lines "input.txt")))
<syntaxhighlight lang="txrlisp">(let ((var (file-get-lines "input.txt")))
(file-put-lines "output.txt" var))</lang>
(file-put-lines "output.txt" var))</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
Line 3,627: Line 3,627:
* Caveat: output.txt will end with a newline, whether or not input.txt ended with one.
* Caveat: output.txt will end with a newline, whether or not input.txt ended with one.


<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh
while IFS= read -r a; do
while IFS= read -r a; do
printf '%s\n' "$a"
printf '%s\n' "$a"
done <input.txt >output.txt</lang>
done <input.txt >output.txt</syntaxhighlight>


Another way, using the 'cat' program
Another way, using the 'cat' program


<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh
cat input.txt >output.txt</lang>
cat input.txt >output.txt</syntaxhighlight>


Yet another way, using the 'cp' utility
Yet another way, using the 'cp' utility
<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh
cp input.txt output.txt</lang>
cp input.txt output.txt</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>decl file input output
<syntaxhighlight lang="ursa">decl file input output
decl string contents
decl string contents
input.open "input.txt"
input.open "input.txt"
Line 3,648: Line 3,648:
output.open "output.txt"
output.open "output.txt"
set contents (input.readall)
set contents (input.readall)
out contents output</lang>
out contents output</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
Line 3,658: Line 3,658:
Returning a copy of the input file with a new name causes it to be
Returning a copy of the input file with a new name causes it to be
written as a new file.
written as a new file.
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std


#executable ('parameterized','')
#executable ('parameterized','')


fileio = ~command.files; &h.path.&h:= 'output.txt'!</lang>
fileio = ~command.files; &h.path.&h:= 'output.txt'!</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit


Sub Main()
Sub Main()
Line 3,691: Line 3,691:
Print #FF, s
Print #FF, s
Close #FF
Close #FF
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
one liner (-2 for system default encoding)
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>
<syntaxhighlight lang="vb">CreateObject("Scripting.FileSystemObject").OpenTextFile("output.txt",2,-2).Write CreateObject("Scripting.FileSystemObject").OpenTextFile("input.txt", 1, -2).ReadAll</syntaxhighlight>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
An edit buffer is normally used as "string variable" in Vedit.
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.
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")
<syntaxhighlight lang="vedit">File_Open("input.txt")
File_Save_As("output.txt", NOMSG)
File_Save_As("output.txt", NOMSG)
Buf_Close(NOMSG) </lang>
Buf_Close(NOMSG) </syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
{{works with|Visual Basic .NET|9.0+}}


<lang vbnet>'byte copy
<syntaxhighlight lang="vbnet">'byte copy
My.Computer.FileSystem.WriteAllBytes("output.txt", _
My.Computer.FileSystem.WriteAllBytes("output.txt", _
My.Computer.FileSystem.ReadAllBytes("input.txt"), False)
My.Computer.FileSystem.ReadAllBytes("input.txt"), False)
Line 3,723: Line 3,723:
output.WriteLine(input.ReadLine)
output.WriteLine(input.ReadLine)
Loop
Loop
End Using</lang>
End Using</syntaxhighlight>


=={{header|Wart}}==
=={{header|Wart}}==
<lang wart>with infile "input.txt"
<syntaxhighlight lang="wart">with infile "input.txt"
with outfile "output.txt"
with outfile "output.txt"
whilet line (read_line)
whilet line (read_line)
prn line</lang>
prn line</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "io" for File
<syntaxhighlight lang="ecmascript">import "io" for File


var contents = File.read("input.txt")
var contents = File.read("input.txt")
File.create("output.txt") {|file|
File.create("output.txt") {|file|
file.writeBytes(contents)
file.writeBytes(contents)
}</lang>
}</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
Usage: fileio <input.txt >output.txt
Usage: fileio <input.txt >output.txt


<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int I, C;
int I, C;
char IntermediateVariable;
char IntermediateVariable;
Line 3,756: Line 3,756:
ChOut(0, C);
ChOut(0, C);
until C = $1A; \EOF
until C = $1A; \EOF
]</lang>
]</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>var d=File("input.txt").read();
<syntaxhighlight lang="zkl">var d=File("input.txt").read();
(f:=File("output.txt","w")).write(d); f.close(); // one read, one write copy
(f:=File("output.txt","w")).write(d); f.close(); // one read, one write copy
File("output.txt").pump(Console); // verify by printing</lang>
File("output.txt").pump(Console); // verify by printing</syntaxhighlight>
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.
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.
<lang zkl>var in=File("input.txt"), out=File("output.txt","w");
<syntaxhighlight lang="zkl">var in=File("input.txt"), out=File("output.txt","w");
foreach line in (in) { out.write(line) } // copy line by line
foreach line in (in) { out.write(line) } // copy line by line
out.close(); // or out=Void and let GC close the file</lang>
out.close(); // or out=Void and let GC close the file</syntaxhighlight>
<lang zkl>fin,fout:=File("input.txt","rb"), File("output.txt","wb"); // copy in chunks, implicit buffer
<syntaxhighlight 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();</lang>
fin.pump(Data(0d524_287),fout); fin.close(); fout.close();</syntaxhighlight>
<lang zkl>// copy in chunks, let GC close file handles
<syntaxhighlight lang="zkl">// copy in chunks, let GC close file handles
File("input.txt","rb").pump(Data(0d524_287),File("output.txt","wb"));</lang>
File("input.txt","rb").pump(Data(0d524_287),File("output.txt","wb"));</syntaxhighlight>
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):
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):
<lang zkl>File("input.txt").pump(Data(),File("output.txt","w"),"text","toUpper");</lang>
<syntaxhighlight lang="zkl">File("input.txt").pump(Data(),File("output.txt","w"),"text","toUpper");</syntaxhighlight>


=={{header|Zig}}==
=={{header|Zig}}==
<lang zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");


pub fn main() !void {
pub fn main() !void {
Line 3,789: Line 3,789:
try file_writer.writeAll(buf[0..read]);
try file_writer.writeAll(buf[0..read]);
}
}
}</lang>
}</syntaxhighlight>


{{omit from|HTML}}
{{omit from|HTML}}