File input/output: Difference between revisions
Content added Content deleted
(add Zig example) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 14: | Line 14: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
< |
<syntaxhighlight lang="11l">V file_contents = File(‘input.txt’).read() |
||
File(‘output.txt’, ‘w’).write(file_contents)</ |
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}}== |
||
< |
<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)))</ |
(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}} |
||
< |
<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</ |
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: |
||
< |
<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;</ |
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: |
||
< |
<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;</ |
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.) |
||
< |
<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;</ |
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. |
||
< |
<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;</ |
end Using_Text_Streams;</syntaxhighlight> |
||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<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'); |
||
}</ |
}</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]}} |
||
< |
<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") |
||
)</ |
)</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<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"</ |
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}}== |
||
< |
<syntaxhighlight lang="rebol">source: read "input.txt" |
||
write "output.txt" source |
write "output.txt" source |
||
print source</ |
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. |
||
< |
<syntaxhighlight lang="autohotkey">Loop, Read, input.txt, output.txt |
||
FileAppend, %A_LoopReadLine%`n</ |
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. |
||
< |
<syntaxhighlight lang="autohotkey">FileRead, var, input.txt |
||
FileAppend, %var%, output.txt</ |
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. |
||
< |
<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) |
||
< |
<syntaxhighlight lang="awk">BEGIN { |
||
while ( (getline <"input.txt") > 0 ) { |
while ( (getline <"input.txt") > 0 ) { |
||
print >"output.txt" |
print >"output.txt" |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
< |
<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" <<< })</ |
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}} |
||
< |
<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</ |
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. |
||
< |
<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}}=== |
||
< |
<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}}=== |
||
< |
<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</ |
close 2</syntaxhighlight> |
||
==={{header|Commodore BASIC}}=== |
==={{header|Commodore BASIC}}=== |
||
< |
<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</ |
130 end</syntaxhighlight> |
||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<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</ |
230 END HANDLER</syntaxhighlight> |
||
==={{header|QBasic}}=== |
==={{header|QBasic}}=== |
||
< |
<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</ |
END</syntaxhighlight> |
||
==={{header|True BASIC}}=== |
==={{header|True BASIC}}=== |
||
< |
<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</ |
END</syntaxhighlight> |
||
==={{header|Yabasic}}=== |
==={{header|Yabasic}}=== |
||
< |
<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</ |
close #2</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
<lang |
<syntaxhighlight lang="dos">copy input.txt output.txt</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="dos">type input.txt > output.txt</syntaxhighlight> |
||
or |
or |
||
< |
<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 |
<syntaxhighlight lang="bbcbasic">*COPY input.txt output.txt</syntaxhighlight> |
||
Alternatively the copy can be done explicitly: |
Alternatively the copy can be done explicitly: |
||
< |
<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%</ |
CLOSE #outfile%</syntaxhighlight> |
||
=={{header|BCPL}}== |
=={{header|BCPL}}== |
||
< |
<syntaxhighlight lang="bcpl">GET "libhdr" |
||
LET start() BE $( |
LET start() BE $( |
||
Line 967: | Line 967: | ||
endwrite() |
endwrite() |
||
$) |
$) |
||
$)</ |
$)</syntaxhighlight> |
||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
{{works with|CCBI|2.1}} |
{{works with|CCBI|2.1}} |
||
< |
<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}}== |
||
< |
<syntaxhighlight lang="bracmat">put$(get$"input.txt","output.txt",NEW)</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<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; |
||
}</ |
}</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}} |
||
< |
<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; |
||
}</ |
}</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:< |
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; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
Line 1,080: | Line 1,080: | ||
The long way: |
The long way: |
||
< |
<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); |
||
}</ |
}</syntaxhighlight> |
||
The short way: |
The short way: |
||
< |
<syntaxhighlight lang="csharp">using System.IO; |
||
var text = File.ReadAllText("input.txt"); |
var text = File.ReadAllText("input.txt"); |
||
File.WriteAllText("output.txt", text);</ |
File.WriteAllText("output.txt", text);</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{works with|g++|3.4.2}} |
{{works with|g++|3.4.2}} |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <fstream> |
#include <fstream> |
||
#include <string> |
#include <string> |
||
Line 1,125: | Line 1,125: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
Simpler version: |
Simpler version: |
||
< |
<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; |
||
}</ |
}</syntaxhighlight> |
||
Using istream- and ostream- iterators: |
Using istream- and ostream- iterators: |
||
< |
<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)); |
||
}</ |
}</syntaxhighlight> |
||
Even simpler way: |
Even simpler way: |
||
< |
<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(); |
||
}</ |
}</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. |
||
< |
<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</ |
= 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. |
||
< |
<syntaxhighlight lang="clean">Start world = copyFile "input.txt" "output.txt" world</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<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> |
|||
< |
<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" |
||
< |
<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. </ |
end program copyfile. </syntaxhighlight> |
||
===Implementation=== |
===Implementation=== |
||
{{works with|OpenCOBOL}} |
{{works with|OpenCOBOL}} |
||
< |
<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 |
||
.</ |
.</syntaxhighlight> |
||
===Built-in Subroutines=== |
===Built-in Subroutines=== |
||
{{works with|OpenCOBOL}} |
{{works with|OpenCOBOL}} |
||
{{works with|Visual COBOL}} |
{{works with|Visual COBOL}} |
||
< |
<syntaxhighlight lang="cobol">*> Originally from ACUCOBOL-GT |
||
CALL "C$COPY" USING "input.txt", "output.txt", 0</ |
CALL "C$COPY" USING "input.txt", "output.txt", 0</syntaxhighlight> |
||
< |
<syntaxhighlight lang="cobol">*> Originally from Micro Focus COBOL |
||
CALL "CBL_COPY_FILE" USING "input.txt", "output.txt"</ |
CALL "CBL_COPY_FILE" USING "input.txt", "output.txt"</syntaxhighlight> |
||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
< |
<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></ |
</cfif></syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 1,340: | Line 1,340: | ||
By lines: |
By lines: |
||
< |
<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))))</ |
do (write-line line out))))</syntaxhighlight> |
||
By arbitrary blocks and for possibly-binary files: |
By arbitrary blocks and for possibly-binary files: |
||
< |
<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))))</ |
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}} |
||
< |
<syntaxhighlight lang="d">import std.file: copy; |
||
void main() { |
void main() { |
||
copy("input.txt", "output.txt"); |
copy("input.txt", "output.txt"); |
||
}</ |
}</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: |
||
< |
<syntaxhighlight lang="d">import std.stdio; |
||
int main() { |
int main() { |
||
Line 1,396: | Line 1,396: | ||
return 0; |
return 0; |
||
}</ |
}</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): |
||
< |
<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; |
||
}</ |
}</syntaxhighlight> |
||
Or a shorter example without explicitly closing the output file: |
Or a shorter example without explicitly closing the output 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; |
||
}</ |
}</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</ |
STOP</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>00001Alan Turing London |
<pre>00001Alan Turing London |
||
Line 1,532: | Line 1,532: | ||
=={{header|DCL}}== |
=={{header|DCL}}== |
||
< |
<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</ |
$ close output</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
Line 1,577: | Line 1,577: | ||
'''- Text File I/O -''' |
'''- Text File I/O -''' |
||
< |
<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;</ |
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. |
||
< |
<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;</ |
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. |
||
< |
<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;</ |
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}} |
||
< |
<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}}== |
||
< |
<syntaxhighlight lang="eiffel ">class |
||
APPLICATION |
APPLICATION |
||
Line 1,702: | Line 1,702: | ||
output_file: PLAIN_TEXT_FILE |
output_file: PLAIN_TEXT_FILE |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 4.x : |
ELENA 4.x : |
||
< |
<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); |
||
}</ |
}</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. |
||
< |
<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")</ |
FileReadWrite.copy("input.txt","output.txt")</syntaxhighlight> |
||
'''Built in function:''' |
'''Built in function:''' |
||
< |
<syntaxhighlight lang="elixir">File.cp!("input.txt", "output.txt")</syntaxhighlight> |
||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<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}}== |
||
< |
<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}} |
||
< |
<syntaxhighlight lang="euphoria">include std/io.e |
||
write_lines("output.txt", read_lines("input.txt"))</ |
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}} |
||
< |
<syntaxhighlight lang="euphoria">integer in,out |
||
object line |
object line |
||
Line 1,782: | Line 1,782: | ||
close(out) |
close(out) |
||
close(in)</ |
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... |
||
< |
<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: |
||
< |
<syntaxhighlight lang="factor">"input.txt" binary file-contents |
||
"output.txt" binary set-file-contents</ |
"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: |
||
< |
<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: |
||
< |
<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. |
||
< |
<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</ |
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</ |
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. |
||
< |
<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</ |
end program FileIO</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
/' |
/' |
||
Line 1,895: | Line 1,895: | ||
Close #2 |
Close #2 |
||
Close #1</ |
Close #1</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,908: | Line 1,908: | ||
=={{header|Frink}}== |
=={{header|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}}== |
||
< |
<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</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,934: | Line 1,934: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<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;</ |
end;</syntaxhighlight> |
||
=={{header|GML}}== |
=={{header|GML}}== |
||
< |
<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);</ |
file_text_close(file);</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,988: | Line 1,988: | ||
fmt.Println(err) |
fmt.Println(err) |
||
} |
} |
||
}</ |
}</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. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 2,026: | Line 2,026: | ||
log.Fatal(err) |
log.Fatal(err) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Using File |
Using File |
||
< |
<syntaxhighlight lang="groovy">content = new File('input.txt').text |
||
new File('output.txt').write(content)</ |
new File('output.txt').write(content)</syntaxhighlight> |
||
Using Ant |
Using Ant |
||
< |
<syntaxhighlight lang="groovy">new AntBuilder().copy(file:'input.txt', toFile:'output.txt', overwrite:true)</syntaxhighlight> |
||
Buffered |
Buffered |
||
< |
<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 } |
||
}</ |
}</syntaxhighlight> |
||
=={{header|GUISS}}== |
=={{header|GUISS}}== |
||
< |
<syntaxhighlight lang="guiss">Start,My Documents,Rightclick:input.txt,Copy,Menu,Edit,Paste, |
||
Rightclick:Copy of input.txt,Rename,Type:output.txt[enter]</ |
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. |
||
< |
<syntaxhighlight lang="haskell">main = readFile "input.txt" >>= writeFile "output.txt"</syntaxhighlight> |
||
=={{header|hexiscript}}== |
=={{header|hexiscript}}== |
||
< |
<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</ |
close in; close out</syntaxhighlight> |
||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
Copy via system call: |
Copy via system call: |
||
< |
<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)</ |
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 |
||
< |
<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)</ |
22 WRITE(FIle=output, CLoSe=1)</syntaxhighlight> |
||
Read and write in 1 block |
Read and write in 1 block |
||
< |
<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</ |
WRITE(FIle=output, CLoSe=1) c END</syntaxhighlight> |
||
=={{header|i}}== |
=={{header|i}}== |
||
< |
<syntaxhighlight lang="i">software { |
||
file = load("input.txt") |
file = load("input.txt") |
||
open("output.txt").write(file) |
open("output.txt").write(file) |
||
} </ |
} </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(). |
||
< |
<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</ |
end</syntaxhighlight> |
||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
< |
<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</ |
close,/all</syntaxhighlight> |
||
=={{header|Io}}== |
=={{header|Io}}== |
||
< |
<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}}== |
||
< |
<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>: |
||
< |
<syntaxhighlight lang="j">require 'files' |
||
'output.txt' (fwrite~ fread) 'input.txt'</ |
'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. |
||
< |
<syntaxhighlight lang="java">import java.io.*; |
||
public class FileIODemo { |
public class FileIODemo { |
||
Line 2,153: | Line 2,153: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
This version closes both files after without OS intervention. |
This version closes both files after without OS intervention. |
||
< |
<syntaxhighlight lang="java">import java.io.*; |
||
public class FileIODemo2 { |
public class FileIODemo2 { |
||
Line 2,186: | Line 2,186: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{works with|Java|1.4}} |
{{works with|Java|1.4}} |
||
'''Package''' [[nio]] |
'''Package''' [[nio]] |
||
< |
<syntaxhighlight lang="java">import java.io.*; |
||
import java.nio.channels.*; |
import java.nio.channels.*; |
||
Line 2,216: | Line 2,216: | ||
} |
} |
||
} |
} |
||
}</ |
}</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. |
||
< |
<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(); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{works with|Java|7+}} |
{{works with|Java|7+}} |
||
< |
<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); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
{{works with|JScript}} |
{{works with|JScript}} |
||
< |
<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();</ |
f_out.Close();</syntaxhighlight> |
||
{{works with|Node.js}} |
{{works with|Node.js}} |
||
< |
<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: |
||
< |
<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:< |
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. |
||
< |
<syntaxhighlight lang="julia">mystring = read("file1", String) |
||
open(io->write(io, mystring), "file2", "w")</ |
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. |
||
< |
<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. |
||
< |
<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)</ |
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. |
||
< |
<syntaxhighlight lang="julia">open(IO ->write(IO, read("file1", String)), "file2", "w")</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
< |
<syntaxhighlight lang="k">`output.txt 0:0:`input.txt</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<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) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|LabVIEW}}== |
=={{header|LabVIEW}}== |
||
Line 2,317: | Line 2,317: | ||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<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</ |
'output.txt 'input.txt copy-file</syntaxhighlight> |
||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<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</ |
end</syntaxhighlight> |
||
=={{header|Lingo}}== |
=={{header|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</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lingo">data = getBytes("input.txt") |
||
putBytes("output.txt", data)</ |
putBytes("output.txt", data)</syntaxhighlight> |
||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
< |
<syntaxhighlight lang="lisaac">Section Header |
||
+ name := FILE_IO; |
+ name := FILE_IO; |
||
Line 2,410: | Line 2,410: | ||
}; |
}; |
||
}; |
}; |
||
);</ |
);</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
{{works with|UCB Logo}} |
{{works with|UCB Logo}} |
||
< |
<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</ |
copy "input.txt "output.txt</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|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}}== |
||
< |
<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"]</ |
CopyFile["input.txt", "output.txt"]</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<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</ |
close outFile</syntaxhighlight> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
< |
<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).</ |
io.set_exit_status(1, !IO).</syntaxhighlight> |
||
=={{header|mIRC Scripting Language}}== |
=={{header|mIRC Scripting Language}}== |
||
{{works with|mIRC}} |
{{works with|mIRC}} |
||
< |
<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) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
< |
<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.</ |
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}} |
||
< |
<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)</ |
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. |
||
< |
<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): |
||
< |
<syntaxhighlight lang="nim">import os |
||
copyfile("input.txt", "output.txt")</ |
copyfile("input.txt", "output.txt")</syntaxhighlight> |
||
Buffer for the entire file: |
Buffer for the entire file: |
||
< |
<syntaxhighlight lang="nim">let x = readFile("input.txt") |
||
writeFile("output.txt", x)</ |
writeFile("output.txt", x)</syntaxhighlight> |
||
Line by line: |
Line by line: |
||
< |
<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()</ |
o.close()</syntaxhighlight> |
||
With a fixed sized buffer: |
With a fixed sized buffer: |
||
< |
<syntaxhighlight lang="nim">const size = 4096 |
||
var |
var |
||
Line 2,662: | Line 2,662: | ||
i.close() |
i.close() |
||
o.close()</ |
o.close()</syntaxhighlight> |
||
Using memory mapping: |
Using memory mapping: |
||
< |
<syntaxhighlight lang="nim">import memfiles |
||
var |
var |
||
Line 2,675: | Line 2,675: | ||
i.close() |
i.close() |
||
o.close()</ |
o.close()</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">use IO; |
||
bundle Default { |
bundle Default { |
||
Line 2,697: | Line 2,697: | ||
} |
} |
||
} |
} |
||
}</ |
}</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: |
||
< |
<syntaxhighlight lang="pascal">uses |
||
classes; |
classes; |
||
begin |
begin |
||
Line 2,713: | Line 2,713: | ||
Free; |
Free; |
||
end; |
end; |
||
end;</ |
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: |
||
< |
<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: |
||
< |
<syntaxhighlight lang="objc">NSData *data = [NSData dataWithContentsOfFile:@"input.txt"]; |
||
[data writeToFile:@"output.txt" atomically:YES];</ |
[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: |
||
< |
<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; |
||
;;</ |
;;</syntaxhighlight> |
||
By character: |
By character: |
||
< |
<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; |
||
;;</ |
;;</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}}== |
||
< |
<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}}== |
||
< |
<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 ;</ |
f close g close ;</syntaxhighlight> |
||
Usage : |
Usage : |
||
< |
<syntaxhighlight lang="oforth">fcopy("input.txt", "output.txt")</syntaxhighlight> |
||
=={{header|OpenEdge/Progress}}== |
=={{header|OpenEdge/Progress}}== |
||
< |
<syntaxhighlight lang="progress (openedge abl)">COPY-LOB FROM FILE "input.txt" TO FILE "output.txt".</syntaxhighlight> |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<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}</ |
{In close}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">f=read("filename.in"); |
||
write("filename.out", f);</ |
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}} |
||
< |
<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;</ |
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) |
||
<!--< |
<!--<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;">) |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
line-by-line (text files only) |
line-by-line (text files only) |
||
<!--< |
<!--<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;">) |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
byte-by-byte (safe on binary files) |
byte-by-byte (safe on binary files) |
||
<!--< |
<!--<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;">) |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
{{works with|PHP|4}} |
{{works with|PHP|4}} |
||
< |
<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); |
||
?></ |
?></syntaxhighlight> |
||
{{works with|PHP|5}} |
{{works with|PHP|5}} |
||
< |
<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.'); |
||
} |
} |
||
?></ |
?></syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
===Using a variable=== |
===Using a variable=== |
||
< |
<syntaxhighlight lang="picolisp">(let V (in "input.txt" (till)) |
||
(out "output.txt" (prin V)) )</ |
(out "output.txt" (prin V)) )</syntaxhighlight> |
||
===Skipping intermediate variable=== |
===Skipping intermediate variable=== |
||
< |
<syntaxhighlight lang="picolisp">(in "input.txt" |
||
(out "output.txt" |
(out "output.txt" |
||
(echo) ) )</ |
(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}}== |
||
< |
<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: |
||
< |
<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;</ |
endwhile;</syntaxhighlight> |
||
Low level block copy: |
Low level block copy: |
||
< |
<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;</ |
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. |
||
< |
<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 |
||
< |
<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 |
||
< |
<syntaxhighlight lang="purebasic">CopyFile("input.txt","output.txt")</syntaxhighlight> |
||
Line by line |
Line by line |
||
< |
<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</ |
EndIf</syntaxhighlight> |
||
Reading & writing the complete file in one pass |
Reading & writing the complete file in one pass |
||
< |
<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</ |
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). |
||
< |
<syntaxhighlight lang="python">import shutil |
||
shutil.copyfile('input.txt', 'output.txt')</ |
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: |
||
< |
<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()</ |
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: |
||
< |
<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()</ |
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: |
||
< |
<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)</ |
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>. |
||
< |
<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") |
||
< |
<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)</ |
close(src); close(dest)</syntaxhighlight> |
||
If the files are not textual but "generic": |
If the files are not textual but "generic": |
||
< |
<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)</ |
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> |
||
< |
<syntaxhighlight lang="rsplus">file.copy("input.txt", "output.txt", overwrite = FALSE)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|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)))</ |
(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 |
<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 |
<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;</ |
$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. |
||
< |
<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</ |
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.) |
||
< |
<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</ |
File2.Close</syntaxhighlight> |
||
=={{header|Raven}}== |
=={{header|Raven}}== |
||
< |
<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}}== |
||
< |
<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</ |
write %output.txt file</syntaxhighlight> |
||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
< |
<syntaxhighlight lang="retro">with files' |
||
here dup "input.txt" slurp "output.txt" spew</ |
here dup "input.txt" slurp "output.txt" spew</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 3,240: | Line 3,240: | ||
The two ''best programming practice'' REXX statements are only needed if there is another calling program in the invocation chain |
The two ''best programming practice'' 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. |
||
< |
<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.*/</ |
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). |
||
< |
<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 */</ |
Call charout ofid,s /* write to output file */</syntaxhighlight> |
||
=={{header|Ring}}== |
=={{header|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. |
||
< |
<syntaxhighlight lang="ruby">str = File.open('input.txt', 'rb') {|f| f.read} |
||
File.open('output.txt', 'wb') {|f| f.write str}</ |
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.) |
||
< |
<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}</ |
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. |
||
< |
<syntaxhighlight lang="ruby">require 'fileutils' |
||
FileUtils.copy_file 'input.txt', 'output.txt'</ |
FileUtils.copy_file 'input.txt', 'output.txt'</syntaxhighlight> |
||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<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}}== |
||
< |
<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: |
||
< |
<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); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
{{libheader|Scala}} |
{{libheader|Scala}} |
||
< |
<syntaxhighlight lang="scala">import java.io.{ FileNotFoundException, PrintWriter } |
||
object FileIO extends App { |
object FileIO extends App { |
||
Line 3,385: | Line 3,385: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
Character by character copy< |
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. |
||
< |
<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;</ |
end func;</syntaxhighlight> |
||
=={{header|SenseTalk}}== |
=={{header|SenseTalk}}== |
||
Reading the file all at once: |
Reading the file all at once: |
||
< |
<syntaxhighlight lang="sensetalk">put file "input.txt" into fileContents |
||
put fileContents into file "output.txt"</ |
put fileContents into file "output.txt"</syntaxhighlight> |
||
Reading the file line by line: |
Reading the file line by line: |
||
< |
<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</ |
close file outputFile</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<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); |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<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]]</ |
in >> out]]</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<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) |
||
]</ |
]</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. |
||
< |
<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. |
||
< |
<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}}== |
||
< |
<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</ |
end</syntaxhighlight> |
||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
{{works with|SML/NJ|110.59}} |
{{works with|SML/NJ|110.59}} |
||
< |
<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;</ |
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. |
||
< |
<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</ |
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}} |
||
< |
<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</ |
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): |
||
< |
<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</ |
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: |
||
< |
<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> |
||
< |
<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</ |
close $myfile</syntaxhighlight> |
||
;Reading a line from a file<nowiki>:</nowiki> |
;Reading a line from a file<nowiki>:</nowiki> |
||
< |
<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</ |
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: |
||
< |
<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</ |
} 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: |
||
< |
<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</ |
] is copy-file</syntaxhighlight> |
||
And a test: |
And a test: |
||
< |
<syntaxhighlight lang="toka">" input.txt" " output.txt" copy-file</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|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: |
||
< |
<syntaxhighlight lang="txrlisp">(let ((var (file-get-string "input.txt"))) |
||
(file-put-string "output.txt" var))</ |
(file-put-string "output.txt" var))</syntaxhighlight> |
||
As a list of lines: |
As a list of lines: |
||
< |
<syntaxhighlight lang="txrlisp">(let ((var (file-get-lines "input.txt"))) |
||
(file-put-lines "output.txt" var))</ |
(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. |
||
< |
<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</ |
done <input.txt >output.txt</syntaxhighlight> |
||
Another way, using the 'cat' program |
Another way, using the 'cat' program |
||
< |
<syntaxhighlight lang="bash">#!/bin/sh |
||
cat input.txt >output.txt</ |
cat input.txt >output.txt</syntaxhighlight> |
||
Yet another way, using the 'cp' utility |
Yet another way, using the 'cp' utility |
||
< |
<syntaxhighlight lang="bash">#!/bin/sh |
||
cp input.txt output.txt</ |
cp input.txt output.txt</syntaxhighlight> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<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</ |
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. |
||
< |
<syntaxhighlight lang="ursala">#import std |
||
#executable ('parameterized','') |
#executable ('parameterized','') |
||
fileio = ~command.files; &h.path.&h:= 'output.txt'!</ |
fileio = ~command.files; &h.path.&h:= 'output.txt'!</syntaxhighlight> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<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</ |
End Sub</syntaxhighlight> |
||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
one liner (-2 for system default encoding) |
one liner (-2 for system default encoding) |
||
< |
<syntaxhighlight lang="vb">CreateObject("Scripting.FileSystemObject").OpenTextFile("output.txt",2,-2).Write CreateObject("Scripting.FileSystemObject").OpenTextFile("input.txt", 1, -2).ReadAll</syntaxhighlight> |
||
=={{header|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. |
||
< |
<syntaxhighlight lang="vedit">File_Open("input.txt") |
||
File_Save_As("output.txt", NOMSG) |
File_Save_As("output.txt", NOMSG) |
||
Buf_Close(NOMSG) </ |
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+}} |
||
< |
<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</ |
End Using</syntaxhighlight> |
||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
< |
<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</ |
prn line</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<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) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
Usage: fileio <input.txt >output.txt |
Usage: fileio <input.txt >output.txt |
||
< |
<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 |
||
]</ |
]</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<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</ |
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. |
||
< |
<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</ |
out.close(); // or out=Void and let GC close the file</syntaxhighlight> |
||
< |
<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();</ |
fin.pump(Data(0d524_287),fout); fin.close(); fout.close();</syntaxhighlight> |
||
< |
<syntaxhighlight lang="zkl">// copy in chunks, let GC close file handles |
||
File("input.txt","rb").pump(Data(0d524_287),File("output.txt","wb"));</ |
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): |
||
< |
<syntaxhighlight lang="zkl">File("input.txt").pump(Data(),File("output.txt","w"),"text","toUpper");</syntaxhighlight> |
||
=={{header|Zig}}== |
=={{header|Zig}}== |
||
< |
<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]); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{omit from|HTML}} |
{{omit from|HTML}} |