File input/output: Difference between revisions
m
syntax highlighting fixup automation
(add Zig example) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 14:
=={{header|11l}}==
<
File(‘output.txt’, ‘w’).write(file_contents)</
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program readwrtFile64.s */
Line 171:
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|ACL2}}==
<
(defun read-channel (channel limit state)
Line 212:
(mv-let (contents state)
(read-from-file in (expt 2 40) state)
(write-to-file out contents state)))</
=={{header|Action!}}==
The attached result has been obtained under DOS 2.5.
{{libheader|Action! Tool Kit}}
<
PROC Dir(CHAR ARRAY filter)
Line 272:
PrintF("Dir ""%S""%E",filter)
Dir(filter)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/File_input_output.png Screenshot from Atari 8-bit computer]
Line 297:
Assuming everything is fine and no error handling is required, this solution is sufficient:
<
procedure Read_And_Write_File_Line_By_Line is
Line 326:
Close (Output);
end if;
end Read_And_Write_File_Line_By_Line;</
Expanded with proper error handling and reporting it reads:
<
procedure Read_And_Write_File_Line_By_Line is
Line 380:
Close (Output);
end if;
end Read_And_Write_File_Line_By_Line;</
===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.)
<
procedure Read_And_Write_File_Character_By_Character is
Line 410:
Close (Output);
end if;
end Read_And_Write_File_Character_By_Character;</
===Using Ada.Text_IO.Text_Streams===
Line 416:
The following solution uses stream I/O. Any file of Ada.Text_IO can be used to obtain a corresponding stream. Reading and writing streams is more efficient than reading text files directly, because it skips formatting.
<
with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;
Line 439:
Close (Output);
end if;
end Using_Text_Streams;</
=={{header|Aime}}==
<
text s;
Line 452:
o.text(s);
o.byte('\n');
}</
=={{header|ALGOL 68}}==
Line 460:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<
# note: algol68toc-1.18 - can compile, but not run v1 #
INT errno;
Line 505:
test:(
copy file v2("input.txt","output.txt")
)</
=={{header|AppleScript}}==
<
set filedata to read file src
set outfile to open for access dst with write permission
Line 515:
end copyFile
copyFile from ":input.txt" into ":output.txt"</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 746:
pop {r2,lr}
bx lr
</syntaxhighlight>
=={{header|Arturo}}==
<
write "output.txt" source
print source</
=={{header|AutoHotkey}}==
Method 1: the input file can be processed line by line.
<
FileAppend, %A_LoopReadLine%`n</
Method 2: the input file can be read at once if it is less than 1 GB.
<
FileAppend, %var%, output.txt</
Method 3: the file can be copied without I/O.
<
Binary I/O is possible with [http://www.autohotkey.com/forum/topic4604.html&highlight=binread this] library from Laszlo.
Line 771:
(This does not handle properly binary files)
<
while ( (getline <"input.txt") > 0 ) {
print >"output.txt"
}
}</
=={{header|Babel}}==
<
{ "input.txt" >>> -- File is now on stack
foo set -- File is now in 'foo'
foo "output.txt" <<< })</
The spirit of Babel is to manipulate things on the stack whenever feasible. In this example,
Line 794:
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
DO UNTIL EOF(1)
Line 802:
CLOSE #1
CLOSE #2
SYSTEM</
==={{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.
<
110 O$ = "OUTPUT.TXT"
120 M$ = CHR$(13)
Line 830:
300 IF NOT EOF THEN RESUME
310 PRINT M$D$"CLOSE"
</syntaxhighlight>
==={{header|BaCon}}===
<
text$ = LOAD$("input.txt")
SAVE text$ TO "output.txt"
</syntaxhighlight>
==={{header|BASIC256}}===
<
open 2, "output.txt"
while not eof(1)
Line 846:
end while
close 1
close 2</
==={{header|Commodore BASIC}}===
<
20 print "read seq file input.txt and write to seq file output.txt"
30 open 4,8,4,"input.txt,seq,read"
Line 861:
110 close 4
120 close 8
130 end</
==={{header|IS-BASIC}}===
<
110 OPEN #1:"output.txt"
120 OPEN #2:"input.txt" ACCESS OUTPUT
Line 877:
210 CLOSE #1
220 CLOSE #2
230 END HANDLER</
==={{header|QBasic}}===
<
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
DO UNTIL EOF(1)
Line 888:
CLOSE #1
CLOSE #2
END</
==={{header|True BASIC}}===
<
OPEN #2: NAME "output.txt", CREATE NEWOLD
ERASE #2
Line 900:
CLOSE #1
CLOSE #2
END</
==={{header|Yabasic}}===
<
open "output.txt" for writing as #2
while not eof(1)
Line 910:
wend
close #1
close #2</
=={{header|Batch File}}==
<syntaxhighlight lang
or
<
or
<
There may be other techniques too.
Line 923:
=={{header|BBC BASIC}}==
[[BBC BASIC for Windows]] has a file copy command:
<syntaxhighlight lang
Alternatively the copy can be done explicitly:
<
outfile% = OPENOUT("output.txt")
WHILE NOT EOF#infile%
Line 931:
ENDWHILE
CLOSE #infile%
CLOSE #outfile%</
=={{header|BCPL}}==
<
LET start() BE $(
Line 967:
endwrite()
$)
$)</
=={{header|Befunge}}==
{{works with|CCBI|2.1}}
<
This linear program tries to open "input.txt" as text file (or aborts).
Line 977:
=={{header|Bracmat}}==
<
=={{header|C}}==
<
int main(int argc, char **argv) {
Line 1,006:
fclose(in);
return 0;
}</
A couple of remarks on the preceding example:
Line 1,015:
{{works with|POSIX}}
<
#include <fcntl.h>
#include <sys/types.h>
Line 1,050:
copy_file("infile", "outfile");
return 0;
}</
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:<
{
int ret = 0;
Line 1,074:
if (bi != (void*)-1) munmap(bi, st.st_size);
return ret;
}</
=={{header|C sharp|C#}}==
Line 1,080:
The long way:
<
using (var reader = new StreamReader("input.txt"))
Line 1,087:
var text = reader.ReadToEnd();
writer.Write(text);
}</
The short way:
<
var text = File.ReadAllText("input.txt");
File.WriteAllText("output.txt", text);</
=={{header|C++}}==
{{works with|g++|3.4.2}}
<
#include <fstream>
#include <string>
Line 1,125:
}
return 0;
}</
Simpler version:
<
#include <fstream>
#include <cstdlib>
Line 1,157:
return EXIT_SUCCESS;
}</
Using istream- and ostream- iterators:
<
# include <fstream>
Line 1,170:
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(ofile));
}</
Even simpler way:
<
int main()
Line 1,181:
std::ofstream output("output.txt");
output << input.rdbuf();
}</
=={{header|Clean}}==
Define a function that copies the content from one file to another.
<
copyFile fromPath toPath world
Line 1,204:
# toFile = fwrites buffer toFile
| size buffer < bufferSize = (fromFile, toFile) // we're done
= copyData bufferSize fromFile toFile // continue recursively</
Apply this function to the world to copy a file.
<
=={{header|Clojure}}==
<
(use 'clojure.java.io)
(copy (file "input.txt") (file "output.txt"))
</syntaxhighlight>
<
;; simple file writing
(spit "filename.txt" "your content here")
Line 1,223:
;; simple file reading
(slurp "filename.txt")
</syntaxhighlight>
=={{header|COBOL}}==
Line 1,230:
Flags used for Micro Focus COBOL:
$set ans85 flag"ans85" flagas"s" sequential"line"
<
program-id. copyfile.
environment division.
Line 1,269:
end-read
.
end program copyfile. </
===Implementation===
{{works with|OpenCOBOL}}
<
PROGRAM-ID. file-io.
Line 1,319:
CLOSE in-file, out-file
.</
===Built-in Subroutines===
{{works with|OpenCOBOL}}
{{works with|Visual COBOL}}
<
CALL "C$COPY" USING "input.txt", "output.txt", 0</
<
CALL "CBL_COPY_FILE" USING "input.txt", "output.txt"</
=={{header|ColdFusion}}==
<
<cffile action="read" file="#expandPath('input.txt')#" variable="inputContents">
<cffile action="write" file="#expandPath('output.txt')#" output="#inputContents#">
</cfif></
=={{header|Common Lisp}}==
Line 1,340:
By lines:
<
(with-open-file (out #p"output.txt" :direction :output)
(loop for line = (read-line in nil 'foo)
until (eq line 'foo)
do (write-line line out))))</
By arbitrary blocks and for possibly-binary files:
<
(with-open-file (in #p"input.txt" :direction :input
Line 1,359:
for size = (read-sequence buffer in)
while (plusp size)
do (write-sequence buffer out :end size))))</
If you're on an odd platform which actually stores text/binary/... type information for files and your CL implementation will use this information, then <tt>in</tt> should be opened with <tt>:element-type :default</tt>.
Line 1,366:
{{libheader|Phobos}}
{{works with|D|2}}
<
void main() {
copy("input.txt", "output.txt");
}</
very plainly, with an intermediate variable:
<syntaxhighlight lang="d">
void main() {
import std.file;
Line 1,379:
std.file.write("output.txt", data);
}
</syntaxhighlight>
via an intermediate buffer variable:
<
int main() {
Line 1,396:
return 0;
}</
{{libheader|Tango}}
Line 1,402:
Copy the content from one file to another (exceptions are handled by Tango):
<
void main()
Line 1,410:
to.copy(from).close;
from.close;
}</
Or a shorter example without explicitly closing the output file:
<
void main()
Line 1,418:
auto to = new File("output.txt", File.WriteCreate);
to.copy(new File("input.txt")).close;
}</
=={{header|DBL}}==
<syntaxhighlight lang="dbl">;
; File Input and output examples for DBL version 4 by Dario B.
;
Line 1,520:
QUIT, CLOSE 1
STOP</
{{out}}
<pre>00001Alan Turing London
Line 1,532:
=={{header|DCL}}==
<
$ open /write output output.txt
$ loop:
Line 1,540:
$ done:
$ close input
$ close output</
=={{header|Delphi}}==
Line 1,577:
'''- Text File I/O -'''
<
f : TextFile ;
s : string ;
Line 1,587:
ReadLn(F,S);
CloseFile(
end;</
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.
<
f : File ;
buff : array[1.1024] of byte ;
Line 1,603:
Blockread(f,Buff,SizeOf(Buff),BytesRead);
CloseFile(f);
end;</
'''- Typed File I/O -'''
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.
<
tAddressBook = Record
Line 1,635:
BlockWrite(f,v,1,bytes);
CloseFile(f);
end;</
=={{header|DIBOL-11}}==
<syntaxhighlight lang="dibol-11">
START ;Simple File Input and Output
Line 1,660:
END
</syntaxhighlight>
=={{header|E}}==
{{works with|E-on-Java}}
<
(This version holds the entire contents in memory.)
Line 1,670:
=={{header|Eiffel}}==
<
APPLICATION
Line 1,702:
output_file: PLAIN_TEXT_FILE
end</
=={{header|Elena}}==
ELENA 4.x :
<
public program()
Line 1,713:
File.assign("output.txt").saveContent(text);
}</
=={{header|Elixir}}==
Read in the whole file and write the contents to a new file.
<
def copy(path,new_path) do
case File.read(path) do
Line 1,732:
end
FileReadWrite.copy("input.txt","output.txt")</
'''Built in function:'''
<
=={{header|Emacs Lisp}}==
<
(insert-file-contents "input.txt")
(buffer-string)))
Line 1,745:
(with-temp-file "output.txt"
(insert input))
</syntaxhighlight>
=={{header|Erlang}}==
<
-module( file_io ).
Line 1,757:
{ok, Contents} = file:read_file( "input.txt" ),
ok = file:write_file( "output.txt", Contents ).
</syntaxhighlight>
=={{header|Euphoria}}==
===Read the entire file and then write it===
{{works with|Euphoria|4.0.0}}
<
write_lines("output.txt", read_lines("input.txt"))</
===Line-by-line reading and writing===
{{works with|Euphoria|any}}
<
object line
Line 1,782:
close(out)
close(in)</
=={{header|F Sharp|F#}}==
Using an intermediate variable for the input file content is not ideomatic in functional programming. Nevertheless...
<
let copyFile fromTextFileName toTextFileName =
Line 1,797:
copyFile "input.txt" "output.txt"
0
</syntaxhighlight>
=={{header|Factor}}==
Holds entire file content in memory:
<
"output.txt" binary set-file-contents</
A bit longer, but only holds a small amount of data in memory. If opening the file for writing fails, we want to clean up the file that's open for reading:
<
"input.txt" binary <file-reader> &dispose
"output.txt" binary <file-writer> stream-copy
] with-destructors
</syntaxhighlight>
Possibly cheating:
<
=={{header|Forth}}==
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.
<
: copy-file ( a1 n1 a2 n2 -- )
r/o open-file throw >r
Line 1,829:
\ Invoke it like this:
s" output.txt" s" input.txt" copy-file</
Note the use of "2 pick" to get the input file handle and "3 pick" to get the output file handle. Local or global variables could have been used, but in this implementation simple stack manipulation was chosen. Also, only maxstring bytes are copied at a time, and the global "pad" memory area is used to hold the data. For faster copies, allocating a larger buffer could be advantageous.
Line 1,836:
A good practice is to ask the user the file name he wants to create like in this short example
<syntaxhighlight lang="text">: INPUT$ ( text -- n n )
pad swap accept pad swap ;
cr ." Enter file name : " 20 INPUT$ w/o create-file throw Value fd-out
Line 1,845:
s\" \n" fd-out write-file
close-output
bye</
=={{header|Fortran}}==
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.
<
integer, parameter :: out = 123, in = 124
Line 1,871:
end if
end program FileIO</
=={{header|FreeBASIC}}==
<
/'
Line 1,895:
Close #2
Close #1</
{{out}}
Line 1,908:
=={{header|Frink}}==
<
contents = read["file:input.txt"]
w = new Writer["output.txt"]
w.print[contents]
w.close[]
</syntaxhighlight>
=={{header|Gambas}}==
<
Dim sOutput As String = "Hello "
Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored
Line 1,926:
Print "'output.txt' contains - " & sOutput
End</
Output:
<pre>
Line 1,934:
=={{header|GAP}}==
<
local f, g, line;
f := InputTextFile(src);
Line 1,948:
CloseStream(f);
CloseStream(g);
end;</
=={{header|GML}}==
<
file = file_text_open_read("input.txt");
str = "";
Line 1,969:
file = file_text_open_write("output.txt");
file_text_write_string(file,str);
file_text_close(file);</
=={{header|Go}}==
<
import (
Line 1,988:
fmt.Println(err)
}
}</
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.
<
import (
Line 2,026:
log.Fatal(err)
}
}</
=={{header|Groovy}}==
Using File
<
new File('output.txt').write(content)</
Using Ant
<
Buffered
<
new File('input.txt').withReader( r -> w << r }
}</
=={{header|GUISS}}==
<
Rightclick:Copy of input.txt,Rename,Type:output.txt[enter]</
=={{header|Haskell}}==
Note: this doesn't keep the file in memory. Buffering is provided by lazy evaluation.
<
=={{header|hexiscript}}==
<
let out openout "output.txt"
while !(catch (let c read char in))
write c out
endwhile
close in; close out</
=={{header|HicEst}}==
Copy via system call:
<
SYSTEM(COPY=input//output, ERror=11) ! on error branch to label 11 (not shown)</
Read and write line by line
<
OPEN(FIle=output)
DO i = 1, 1E300 ! "infinite" loop, exited on end-of-file error
Line 2,070:
WRITE(FIle=output, ERror=23) buffer ! on error branch to label 23 (not shown)
ENDDO
22 WRITE(FIle=output, CLoSe=1)</
Read and write in 1 block
<
OPEN(FIle=output, SEQuential, UNFormatted, ERror=32) ! on error branch to label 32 (not shown)
ALLOCATE(c, len)
READ(FIle=input, CLoSe=1) c
WRITE(FIle=output, CLoSe=1) c END</
=={{header|i}}==
<
file = load("input.txt")
open("output.txt").write(file)
} </
=={{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().
<
in := open(f := "input.txt","r") | stop("Unable to open ",f)
out := open(f := "output.txt","w") | stop("Unable to open ",f)
while write(out,read(in))
end</
=={{header|IDL}}==
<
openw,unit1,'output.txt,/get
openr,unit2,'input.txt',/get
Line 2,105:
writeu,unit1,buff
; that's all
close,/all</
=={{header|Io}}==
<
outf := File with("output.txt") openForUpdating
Line 2,118:
inf close
outf close
</syntaxhighlight>
=={{header|J}}==
<
Or using the system library <tt>files</tt>:
<
'output.txt' (fwrite~ fread) 'input.txt'</
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:
Simple version; Files ''may'' be closed automatically by OS, on some systems.
<
public class FileIODemo {
Line 2,153:
}
}
}</
This version closes both files after without OS intervention.
<
public class FileIODemo2 {
Line 2,186:
}
}
}</
{{works with|Java|1.4}}
'''Package''' [[nio]]
<
import java.nio.channels.*;
Line 2,216:
}
}
}</
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.
<
public class Test {
public static void main (String[] args) throws IOException {
Line 2,233:
bw.close();
}
}</
{{works with|Java|7+}}
<
public class Copy{
public static void main(String[] args) throws Exception{
Line 2,243:
Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);
}
}</
=={{header|JavaScript}}==
{{works with|JScript}}
<
var ForReading = 1, ForWriting = 2;
var f_in = fso.OpenTextFile('input.txt', ForReading);
Line 2,261:
f_in.Close();
f_out.Close();</
{{works with|Node.js}}
<
var fs = require('fs');
require('util').pump(fs.createReadStream('input.txt', {flags:'r'}), fs.createWriteStream('output.txt', {flags:'w+'}));
</syntaxhighlight>
=={{header|jq}}==
If the input file consists of ordinary lines of text, then the lines can be copied verbatim, one by one, as follows:
<
</syntaxhighlight>
If the input file consists of JSON entities, and if we wish to "pretty print" each, then the following will suffice:<
jq -M '. as $line | $line' input.txt > output.txt
</syntaxhighlight>
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:
=={{header|Julia}}==
Here we read the content of file1 into the variable mystring. Then we write the content of string to file2.
<
open(io->write(io, mystring), "file2", "w")</
Note however that Julia has a `cp` function to copy the content of a file to another file.
<
We can also open and close the file handles manually.
<
outfile = open("file2", "w")
write(outfile, read(infile, String))
close(outfile)
close(infile)</
Here is a one-liner that guarantees that the file handle is closed
even if something goes wrong during the read/write phase.
<
=={{header|K}}==
<
=={{header|Kotlin}}==
<
import java.io.File
Line 2,310:
val text = File("input.txt").readText()
File("output.txt").writeText(text)
}</
=={{header|LabVIEW}}==
Line 2,317:
=={{header|Lang5}}==
<
: set-file '> swap open ;
: >>contents slurp puts ;
Line 2,323:
swap set-file 'fdst set fdst fout >>contents fdst close ;
'output.txt 'input.txt copy-file</
=={{header|Liberty BASIC}}==
<
open "input.txt" for input as #f1
Line 2,337:
close #f2
end</
=={{header|Lingo}}==
<
-- Returns file as ByteArray
-- @param {string} tFile
Line 2,373:
fp.closeFile()
return true
end</
<
putBytes("output.txt", data)</
=={{header|Lisaac}}==
<
+ name := FILE_IO;
Line 2,410:
};
};
);</
=={{header|Logo}}==
{{works with|UCB Logo}}
<
openread :from
openwrite :to
Line 2,423:
end
copy "input.txt "output.txt</
=={{header|Lua}}==
<
inFile = io.open("input.txt", "r")
data = inFile:read("*all") -- may be abbreviated to "*a";
Line 2,439:
-- Oneliner version:
io.open("output.txt", "w"):write(io.open("input.txt", "r"):read("*a"))
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
Line 2,454:
We can edit thousands of lines. Document is a double linked list.
<syntaxhighlight lang="m2000 interpreter">
Module FileInputOutput {
Edit "Input.txt"
Line 2,465:
}
FileInputOutput
</syntaxhighlight>
===Using Buffer Object===
A buffer expose real pointer (address), so here M(0) is the address of first byte, and Len(m) is the size of buffer in bytes. This buffer is not for code, but for data (no execution allowed).
<syntaxhighlight lang="m2000 interpreter">
Module Using_Buffer {
M=buffer("Input.txt")
Line 2,486:
}
Using_Buffer
</syntaxhighlight>
=={{header|Maple}}==
<syntaxhighlight lang="maple">
inout:=proc(filename)
local f;
Line 2,495:
FileTools[Text][WriteFile]("output.txt",f);
end proc;
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ];
CopyFile["input.txt", "output.txt"]</
=={{header|MAXScript}}==
<
outFile = createFile "output.txt"
while not EOF inFile do
Line 2,510:
)
close inFile
close outFile</
=={{header|Mercury}}==
<
:- interface.
Line 2,552:
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, io.error_message(Error), !IO),
io.set_exit_status(1, !IO).</
=={{header|mIRC Scripting Language}}==
{{works with|mIRC}}
<
.write myfilename.txt Goodbye Mike!
.echo -a Myfilename.txt contains: $read(myfilename.txt,1)
}</
=={{header|Modula-3}}==
<
IMPORT IO, Rd, Wr;
Line 2,581:
Rd.Close(infile);
Wr.Close(outfile);
END FileIO.</
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:
=={{header|Nanoquery}}==
{{trans|Ursa}}
<
input = new(File, "input.txt")
Line 2,596:
contents = input.readAll()
output.write(contents)</
=={{header|NetRexx}}==
{{works with|Java|7}}
Takes advantage of some of the new path and file handling features of [[Java|Java's]] <tt>java.nio</tt> library.
<
options replace format comments java crossref symbols nobinary
Line 2,628:
return
</syntaxhighlight>
=={{header|Nim}}==
Copying the file directly (without buffer):
<
copyfile("input.txt", "output.txt")</
Buffer for the entire file:
<
writeFile("output.txt", x)</
Line by line:
<
i = open("input.txt")
o = open("output.txt", fmWrite)
Line 2,648:
i.close()
o.close()</
With a fixed sized buffer:
<
var
Line 2,662:
i.close()
o.close()</
Using memory mapping:
<
var
Line 2,675:
i.close()
o.close()</
=={{header|Objeck}}==
<
bundle Default {
Line 2,697:
}
}
}</
=={{header|Object Pascal}}==
Line 2,704:
For a more object oriented style one can use a TFilestream:
<
classes;
begin
Line 2,713:
Free;
end;
end;</
=={{header|Objective-C}}==
Line 2,719:
For copying files, using <code>NSFileManager</code> is preferred:
<
If you want to do it manually:
<
[data writeToFile:@"output.txt" atomically:YES];</
Displayed without error checking to make it more clear. In real code you will need to add lot of error checking code, and maybe use <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:
=={{header|OCaml}}==
By line:
<
let ic = open_in "input.txt" in
let oc = open_out "output.txt" in
Line 2,745:
close_in ic;
close_out oc;
;;</
By character:
<
let ic = open_in "input.txt" in
let oc = open_out "output.txt" in
Line 2,759:
close_in ic;
close_out oc;
;;</
(Notice that ic and oc, of type ''in_channel'' and ''out_channel'', are buffered)
=={{header|Octave}}==
<
in = fopen("input.txt", "r", "native");
out = fopen("output.txt", "w","native");
Line 2,792:
fclose(out);
end
</syntaxhighlight>
=={{header|Oforth}}==
<
| f g |
File newMode(in, File.BINARY) dup open(File.READ) ->f
Line 2,802:
while(f >> dup notNull) [ g addChar ] drop
f close g close ;</
Usage :
<
=={{header|OpenEdge/Progress}}==
<
=={{header|Oz}}==
<
class TextFile from Open.file Open.text end
Line 2,827:
{CopyAll In Out}
{Out close}
{In close}</
=={{header|PARI/GP}}==
<
write("filename.out", f);</
=={{header|Pascal}}==
Line 2,840:
{{works with|Perl|5.8.8}}
<
open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!";
Line 2,857:
close $fh_in;
close $fh_out;</
Perl has also a powerful mechanism in conjunction with opening files called IO disciplines. It allows you to automatically apply chainable transformations on the input and output. Mangling newlines, gzip (de)compression and character encoding are the most used examples.
Line 2,864:
{{libheader|Phix/basics}}
whole file as a single string (safe on small binary files)
<!--<
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"input.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"rb"<span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">txt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text<span style="color: #0000FF;">(<span style="color: #000000;">fn<span style="color: #0000FF;">)</span>
Line 2,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;">close<span style="color: #0000FF;">(<span style="color: #000000;">fn<span style="color: #0000FF;">)
<!--</
line-by-line (text files only)
<!--<
<span style="color: #004080;">integer</span> <span style="color: #000000;">infn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"input.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"r"<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span>
<span style="color: #000000;">outfn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"output.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"w"<span style="color: #0000FF;">)</span>
Line 2,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;">outfn<span style="color: #0000FF;">)
<!--</
byte-by-byte (safe on binary files)
<!--<
<span style="color: #004080;">integer</span> <span style="color: #004080;">byte<span style="color: #0000FF;">,</span>
<span style="color: #000000;">infd</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"input.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"rb"<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span>
Line 2,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;">outfd<span style="color: #0000FF;">)
<!--</
=={{header|PHP}}==
{{works with|PHP|4}}
<
if (!$in = fopen('input.txt', 'r')) {
Line 2,919:
fclose($out);
fclose($in);
?></
{{works with|PHP|5}}
<
if ($contents = file_get_contents('input.txt')) {
if (!file_put_contents('output.txt', $contents)) {
Line 2,930:
echo('Could not open input file.');
}
?></
=={{header|PicoLisp}}==
===Using a variable===
<
(out "output.txt" (prin V)) )</
===Skipping intermediate variable===
<
(out "output.txt"
(echo) ) )</
=={{header|Pike}}==
===Line by line===
<syntaxhighlight lang="pike">
object lines = Stdio.File("input.txt")->line_iterator();
object out = Stdio.File("output.txt", "cw");
foreach(lines; int line_number; string line)
out->write(line + "\n");
</syntaxhighlight>
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}}==
<
declare in file, out file;
Line 2,961:
put file (out) edit (line) (A);
end;
</syntaxhighlight>
=={{header|Pop11}}==
Line 2,967:
Char by char copy:
<
lvars o_stream = discout('output.txt');
lvars c;
while (i_stream() ->> c) /= termin do
o_stream(c);
endwhile;</
Low level block copy:
<
lvars o_file = syscreate('output.txt', 1, true);
lvars buff = inits(4096);
Line 2,982:
while (sysread(i_file, buff, length(buff)) ->> i) > 0 do
syswrite(o_file, buff, i);
endwhile;</
=={{header|PowerShell}}==
Line 2,988:
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.
<
Using an alternate cmdlet to write the file
<
=={{header|PureBasic}}==
Line 2,997:
Basic file copy
<
Line by line
<
If in
out = CreateFile(#PB_Any,"output.txt")
Line 3,013:
EndIf
CloseFile(in)
EndIf</
Reading & writing the complete file in one pass
<
Define MyLine$, *Buffer, length
length=FileSize("input.txt")
Line 3,030:
EndIf
CloseFile(0)
EndIf</
=={{header|Python}}==
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).
<
shutil.copyfile('input.txt', 'output.txt')</
However the following example shows how one would do file I/O of other sorts:
<
outfile = open('output.txt', 'w')
for line in infile:
outfile.write(line)
outfile.close()
infile.close()</
This does no error checking. A more robust program would wrap each open with exception handling blocks:
<
try:
infile = open('input.txt', 'r')
Line 3,070:
finally:
infile.close()
outfile.close()</
In Python 2.6 (or 2.5 if we use ''from __future__ import with_statement'') we can more simply write:
<
try:
with open('input.txt') as infile:
Line 3,082:
except IOError:
print >> sys.stderr, "Some I/O Error occurred"
sys.exit(1)</
The files will automatically be closed on exit of their ''with:'' blocks. (Thus even if an I/O error occurred while reading the middle of the input file we are assured that the ''.close()'' method will have been called on each of the two files.
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>.
<
temp put
temp share
$ "output.txt" putfile drop
</syntaxhighlight>
=={{header|R}}==
If files are textual we can use <tt>readLines</tt> ("-1" means "read until the end")
<
dest <- file("output.txt", "w")
fc <- readLines(src, -1)
writeLines(fc, dest)
close(src); close(dest)</
If the files are not textual but "generic":
<
dest <- file("output.txt", "wb")
Line 3,116:
writeBin(v, dest)
}
close(src); close(dest)</
Another simpler way is to use <tt>file.copy</tt>
<
=={{header|Racket}}==
<
(define file-content
(with-input-from-file "input.txt"
Line 3,135:
(with-output-to-file "output.txt"
(lambda ()
(write file-content)))</
=={{header|Raku}}==
Line 3,143:
{{works with|Rakudo|2016.07}}
<syntaxhighlight lang="raku"
Otherwise, copying line-by line:
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku"
my $out = open "output.txt", :w;
for $in.lines -> $line {
Line 3,154:
}
$in.close;
$out.close;</
=={{header|RapidQ}}==
Line 3,162:
The first version copies text line by line, as in the ''BASIC'' example.
<
DIM File1 AS QFileStream
Line 3,176:
File1.Close
File2.Close</
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.)
<
DIM File1 AS QFileStream
Line 3,192:
File1.Close
File2.Close</
=={{header|Raven}}==
<
=={{header|REALbasic}}==
<syntaxhighlight lang="vb">
Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream
Line 3,210:
tos.Close
End Sub
</syntaxhighlight>
=={{header|REBOL}}==
<
; No line translations:
Line 3,220:
; Save a web page:
write/binary %output.html read http://rosettacode.org
</syntaxhighlight>
=={{header|Red}}==
<syntaxhighlight lang="red">
file: read %input.txt
write %output.txt file</
=={{header|Retro}}==
<
here dup "input.txt" slurp "output.txt" spew</
=={{header|REXX}}==
Line 3,240:
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.
<
iFID = 'input.txt' /*the name of the input file. */
oFID = 'output.txt' /* " " " " output " */
Line 3,251:
call lineout iFID /*close input file, just to be safe.*/ /* ◄■■■■■■ best programming practice.*/
call lineout oFID /* " output " " " " " */ /* ◄■■■■■■ best programming practice.*/</
===version 2===
Note that this version is limited to files less than one million bytes (and/or possibly virtual memory).
<
* 03.09.2012 Walter Pachl (without erase string would be appended)
**********************************************************************/
Line 3,262:
'erase' ofid /* avoid appending */
s=charin(ifid,,1000000) /* read the input file */
Call charout ofid,s /* write to output file */</
=={{header|Ring}}==
<
fn1 = "ReadMe.txt"
fn2 = "ReadMe2.txt"
Line 3,285:
fseek(fp,0,c_filestart)
return nfilesize
</syntaxhighlight>
=={{header|Ruby}}==
In general, open both files in binary mode.
<
File.open('output.txt', 'wb') {|f| f.write str}</
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.)
<
# Only if pipe '|' is not first character of path!
str = IO.read('input.txt')
open('output.txt', 'w') {|f| f.write str}</
To copy a file block by block, use FileUtils from the standard library.
<
FileUtils.copy_file 'input.txt', 'output.txt'</
=={{header|Run BASIC}}==
<
fileLen = LOF(#in) 'Length Of File
fileData$ = input$(#in, fileLen) 'read entire file
Line 3,324:
close #in
close #out
</syntaxhighlight>
=={{header|Rust}}==
<
use std::io::{Read, Write};
Line 3,337:
file.write_all(&data).unwrap();
}
</syntaxhighlight>
The above program will panic with any sort of error. The following shows proper error handling:
<
use std::io::{self, Read, Write};
use std::path::Path;
Line 3,366:
writeln!(&mut io::stderr(), "ERROR: {}", msg).expect("Could not write to stdout");
process::exit(code);
}</
=={{header|Scala}}==
{{libheader|Scala}}
<
object FileIO extends App {
Line 3,385:
}
}
}</
=={{header|Scheme}}==
Character by character copy<
(define in-file (open-input-file "input.txt"))
(define out-file (open-output-file "output.txt"))
Line 3,401:
(close-input-port in-file)
(close-output-port out-file)
</syntaxhighlight>
=={{header|Seed7}}==
Line 3,408:
can be used to copy a source file to a destination.
<
include "osfiles.s7i";
Line 3,414:
begin
copyFile("input.txt", "output.txt");
end func;</
=={{header|SenseTalk}}==
Reading the file all at once:
<
put fileContents into file "output.txt"</
Reading the file line by line:
<
put "output.txt" into outputFile
Line 3,434:
close file inputFile
close file outputFile</
=={{header|Sidef}}==
<
var out = %f'output.txt'.open_w;
in.each { |line|
out.print(line);
};</
=={{header|Slate}}==
<
(File newNamed: 'output.txt' &mode: File CreateWrite) sessionDo: [| :out |
in >> out]]</
=={{header|Smalltalk}}==
<
in := FileStream open: 'input.txt' mode: FileStream read.
out := FileStream open: 'output.txt' mode: FileStream write.
Line 3,456:
whileFalse: [
out nextPut: (in next)
]</
=={{header|Snabel}}==
Reads the entire file into into a list of buffers before writing and returns number of bytes written.
<
let: q Bin list;
'input.txt' rfile read {{@q $1 push} when} for
@q 'output.txt' rwfile write
0 $1 &+ for
</syntaxhighlight>
Alternative solution for large files with comparable performance to shell cp; also returns number of bytes written.
<
let: q Bin list;
let: wq @q fifo;
Line 3,480:
@q +? {@w &_ for} when
</syntaxhighlight>
=={{header|SNOBOL4}}==
<
input(.input,5,,'input.txt')
output(.output,6,,'output.txt')
while output = input :s(while)
end</
=={{header|Standard ML}}==
{{works with|SML/NJ|110.59}}
<
let
val instream = TextIO.openIn from
Line 3,500:
in
true
end handle _ => false;</
=={{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.
<
file open fin using `1', read text
file open fout using `2', write text replace
Line 3,517:
end
copyfile input.txt output.txt</
=={{header|Tcl}}==
Line 3,525:
{{works with|tixwish}}
{{works with|tclkit}}
<
set out [open "output.txt" w]
# Obviously, arbitrary transformations could be added to the data at this point
puts -nonewline $out [read $in]
close $in
close $out</
For larger files, it is better to use the <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):
<
set out [open "output.txt" w]
fcopy $in $out
close $in
close $out</
Or the minimal version if we don't need any processing of the data at all:
<
===Other key file I/O operations===
;Writing a line to a file<nowiki>:</nowiki>
<
set myfile [open "README.TXT" w]
#write something to the file
puts $myfile "This is line 1, so hello world...."
#close the file
close $myfile</
;Reading a line from a file<nowiki>:</nowiki>
<
set myfile [open "README.TXT" r]
#read something from the file
Line 3,556:
puts $mydata
#close the file
close $myfile</
=={{header|Toka}}==
This is one method, which works with any type of file:
<
{
value| source dest size buffer |
Line 3,582:
[ source file.close dest file.close ] is close-files
[ prepare [ read-source write-dest close-files ] ifTrue ]
} is copy-file</
And a much simpler way for plain text files, making use of file.slurp:
<
swap file.slurp dup 0 <>
[ >r "W" file.open dup r> string.getLength file.write drop file.close ] ifTrue
] is copy-file</
And a test:
<
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
ERROR/STOP CREATE ("input.txt", seq-o,-std-)
Line 3,607:
path2output=FULLNAME(TUSTEP,"output.txt",-std-)
status=WRITE(path2output,contentinput)
</syntaxhighlight>
=={{header|TXR}}==
Line 3,613:
As a character string:
<
(file-put-string "output.txt" var))</
As a list of lines:
<
(file-put-lines "output.txt" var))</
=={{header|UNIX Shell}}==
Line 3,627:
* Caveat: output.txt will end with a newline, whether or not input.txt ended with one.
<
while IFS= read -r a; do
printf '%s\n' "$a"
done <input.txt >output.txt</
Another way, using the 'cat' program
<
cat input.txt >output.txt</
Yet another way, using the 'cp' utility
<
cp input.txt output.txt</
=={{header|Ursa}}==
<
decl string contents
input.open "input.txt"
Line 3,648:
output.open "output.txt"
set contents (input.readall)
out contents output</
=={{header|Ursala}}==
Line 3,658:
Returning a copy of the input file with a new name causes it to be
written as a new file.
<
#executable ('parameterized','')
fileio = ~command.files; &h.path.&h:= 'output.txt'!</
=={{header|VBA}}==
<
Sub Main()
Line 3,691:
Print #FF, s
Close #FF
End Sub</
=={{header|VBScript}}==
one liner (-2 for system default encoding)
<
=={{header|Vedit macro language}}==
An edit buffer is normally used as "string variable" in Vedit.
To read a file into edit buffer, simply open the file. The file contents can then be modified if required before saving into a new file.
<
File_Save_As("output.txt", NOMSG)
Buf_Close(NOMSG) </
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
<
My.Computer.FileSystem.WriteAllBytes("output.txt", _
My.Computer.FileSystem.ReadAllBytes("input.txt"), False)
Line 3,723:
output.WriteLine(input.ReadLine)
Loop
End Using</
=={{header|Wart}}==
<
with outfile "output.txt"
whilet line (read_line)
prn line</
=={{header|Wren}}==
<
var contents = File.read("input.txt")
File.create("output.txt") {|file|
file.writeBytes(contents)
}</
=={{header|XPL0}}==
Usage: fileio <input.txt >output.txt
<
int I, C;
char IntermediateVariable;
Line 3,756:
ChOut(0, C);
until C = $1A; \EOF
]</
=={{header|zkl}}==
<
(f:=File("output.txt","w")).write(d); f.close(); // one read, one write copy
File("output.txt").pump(Console); // verify by printing</
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.
<
foreach line in (in) { out.write(line) } // copy line by line
out.close(); // or out=Void and let GC close the file</
<
fin.pump(Data(0d524_287),fout); fin.close(); fout.close();</
<
File("input.txt","rb").pump(Data(0d524_287),File("output.txt","wb"));</
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):
<
=={{header|Zig}}==
<
pub fn main() !void {
Line 3,789:
try file_writer.writeAll(buf[0..read]);
}
}</
{{omit from|HTML}}
|