File input/output: Difference between revisions
m
→{{header|Standard ML}}
(18 intermediate revisions by 11 users not shown) | |||
Line 793:
=={{header|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.
Line 847 ⟶ 836:
close 1
close 2</syntaxhighlight>
==={{header|BBC BASIC}}===
[[BBC BASIC for Windows]] has a file copy command:
<syntaxhighlight lang="bbcbasic">*COPY input.txt output.txt</syntaxhighlight>
Alternatively the copy can be done explicitly:
<syntaxhighlight lang="bbcbasic">infile% = OPENIN("input.txt")
outfile% = OPENOUT("output.txt")
WHILE NOT EOF#infile%
BPUT #outfile%, BGET#infile%
ENDWHILE
CLOSE #infile%
CLOSE #outfile%</syntaxhighlight>
==={{header|Commodore BASIC}}===
Line 862 ⟶ 863:
120 close 8
130 end</syntaxhighlight>
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
/'
input.txt contains:
The quick brown fox jumps over the lazy dog.
Empty vessels make most noise.
Too many chefs spoil the broth.
A rolling stone gathers no moss.
'/
Open "output.txt" For Output As #1
Open "input.txt" For Input As #2
Dim line_ As String ' note that line is a keyword
While Not Eof(2)
Line Input #2, line_
Print #1, line_
Wend
Close #2
Close #1</syntaxhighlight>
{{out}}
<pre>
output.txt contains:
The quick brown fox jumps over the lazy dog.
Empty vessels make most noise.
Too many chefs spoil the broth.
A rolling stone gathers no moss.
</pre>
==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">
/*
Rosetta Code File input/output example
FutureBasic 7.0.14
Rich Love
9/25/22
Before running this, use TextEdit to create a file called input.txt on your desktop.
Format as plain text and create a few lines of text.
Then save.
*/
output file "FileInputOutput.app"
CFURLRef ParentDirectory // Create a url for the desktop
ParentDirectory = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask )
CFURLRef inputURL // Create a url for input.txt on the desktop
inputURL = fn URLByAppendingPathComponent( ParentDirectory, @"input.txt" )
CFURLRef outputURL // Create a url for output.txt on the desktop
outputURL = fn URLByAppendingPathComponent( ParentDirectory, @"output.txt" )
open "O", 1, outputURL
open "I", 2, inputURL
str255 dataLine
While Not Eof(2)
Line Input #2, dataLine
Print #1, dataLine
Wend
Close #1
Close #2
end
</syntaxhighlight>
==={{header|Gambas}}===
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sOutput As String = "Hello "
Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored
File.Save(User.Home &/ "output.txt", sOutput)
File.Save(User.Home &/ "input.txt", sOutput & sInput)
Print "'input.txt' contains - " & sOutput & sInput
Print "'output.txt' contains - " & sOutput
End</syntaxhighlight>
Output:
<pre>
'input.txt' contains - Hello World!
'output.txt' contains - Hello
</pre>
==={{header|IS-BASIC}}===
Line 878 ⟶ 974:
220 CLOSE #2
230 END HANDLER</syntaxhighlight>
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">nomainwin
open "input.txt" for input as #f1
qtyBytes = lof( #f1)
source$ = input$( #f1, qtyBytes)
close #f1
open "output.txt" for output as #f2
#f2 source$;
close #f2
end</syntaxhighlight>
==={{header|PureBasic}}===
====Basic file copy====
<syntaxhighlight lang="purebasic">CopyFile("input.txt","output.txt")</syntaxhighlight>
====Line by line====
<syntaxhighlight lang="purebasic">in = ReadFile(#PB_Any,"input.txt")
If in
out = CreateFile(#PB_Any,"output.txt")
If out
Define MyLine$
While Not Eof(in)
MyLine$ = ReadString(in)
WriteString(out,MyLine$)
Wend
CloseFile(out)
EndIf
CloseFile(in)
EndIf</syntaxhighlight>
====Reading & writing the complete file in one pass====
<syntaxhighlight lang="purebasic">If ReadFile(0,"input.txt")
Define MyLine$, *Buffer, length
length=FileSize("input.txt")
*Buffer = AllocateMemory(length)
If *Buffer
If OpenFile(1,"output.txt")
ReadData(0, *Buffer, length)
WriteData(1, *Buffer, length)
CloseFile(1)
EndIf
FreeMemory(*Buffer)
EndIf
CloseFile(0)
EndIf</syntaxhighlight>
==={{header|QBasic}}===
See [[#QuickBASIC|QuickBASIC]].
==={{header|QuickBASIC}}===
{{works with|QuickBasic|4.5}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">
' File input/output
OPEN "INPUT.TXT" FOR INPUT AS #1
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
DO UNTIL EOF(1)
LOOP
CLOSE #1
CLOSE #2
END
</syntaxhighlight>
==={{header|RapidQ}}===
File I/O is one of the things where RapidQ differs from standard Basic. RapidQ uses file streams.
The first version copies text line by line, as in the ''BASIC'' example.
<syntaxhighlight lang="rapidq">$INCLUDE "rapidq.inc"
DIM File1 AS QFileStream
DIM File2 AS QFileStream
File1.Open("input.txt", fmOpenRead)
File2.Open("output.txt", fmCreate)
WHILE NOT File1.EOF
data$ = File1.ReadLine
File2.WriteLine(data$)
WEND
File1.Close
File2.Close</syntaxhighlight>
When just copying data, the code can be simplified by using the CopyFrom method.<br />
(The second parameter for CopyFrom is number of bytes to copy, 0 = copy the whole file.)
<syntaxhighlight lang="rapidq">$INCLUDE "rapidq.inc"
DIM File1 AS QFileStream
DIM File2 AS QFileStream
File1.Open("input.txt", fmOpenRead)
File2.Open("output.txt", fmCreate)
File2.CopyFrom(File1, 0)
File1.Close
File2.Close</syntaxhighlight>
==={{header|REALbasic}}===
<syntaxhighlight lang="vb">
Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream
Dim tos As TextOutputStream
tis = tis.Open(input)
tos = tos.Create(output)
While Not tis.EOF
tos.WriteLine(tis.ReadLine)
Wend
tis.Close
tos.Close
End Sub
</syntaxhighlight>
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="runbasic">open "input.txt" for input as #in
fileLen = LOF(#in) 'Length Of File
fileData$ = input$(#in, fileLen) 'read entire file
close #in
open "output.txt" for output as #out
print #out, fileData$ 'write entire fie
close #out
end
</syntaxhighlight>
Or directly with no intermediate fileData$
{{works with|Just BASIC}}
<syntaxhighlight lang="runbasic">open "input.txt" for input as #in
open "output.txt" for output as #out
fileLen = LOF(#in) 'Length Of File
print #out, input$(#in, fileLen) 'entire file
close #in
close #out
</syntaxhighlight>
==={{header|True BASIC}}===
Line 901 ⟶ 1,130:
CLOSE #2
END</syntaxhighlight>
==={{header|VBA}}===
<syntaxhighlight lang="vb">Option Explicit
Sub Main()
Dim s As String, FF As Integer
'read a file line by line
FF = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF
While Not EOF(FF)
Line Input #FF, s
Debug.Print s
Wend
Close #FF
'read a file
FF = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF
s = Input(LOF(1), #FF)
Close #FF
Debug.Print s
'write a file
FF = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\output.txt" For Output As #FF
Print #FF, s
Close #FF
End Sub</syntaxhighlight>
==={{header|VBScript}}===
One liner (-2 for system default encoding)
<syntaxhighlight lang="vb">CreateObject("Scripting.FileSystemObject").OpenTextFile("output.txt",2,-2).Write CreateObject("Scripting.FileSystemObject").OpenTextFile("input.txt", 1, -2).ReadAll</syntaxhighlight>
==={{header|Visual Basic .NET}}===
{{works with|Visual Basic .NET|9.0+}}
====Byte copy====
<syntaxhighlight lang="vbnet">My.Computer.FileSystem.WriteAllBytes("output.txt", _
My.Computer.FileSystem.ReadAllBytes("input.txt"), False)
</syntaxhighlight>
====Text copy====
<syntaxhighlight lang="vbnet">Using input = IO.File.OpenText("input.txt"), _
output As New IO.StreamWriter(IO.File.OpenWrite("output.txt"))
output.Write(input.ReadToEnd)
End Using</syntaxhighlight>
====Line by line text copy====
<syntaxhighlight lang="vbnet">Using input = IO.File.OpenText("input.txt"), _
output As New IO.StreamWriter(IO.File.OpenWrite("output.txt"))
Do Until input.EndOfStream
output.WriteLine(input.ReadLine)
Loop
End Using</syntaxhighlight>
==={{header|Yabasic}}===
Line 920 ⟶ 1,203:
There may be other techniques too.
=={{header|BCPL}}==
Line 1,845 ⟶ 2,116:
w/o create-file throw r>
begin
pad
?dup while
pad swap 3 pick write-file throw
repeat
Line 1,855 ⟶ 2,126:
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
Also, abort" can be used instead of throw if desired.
Line 1,896 ⟶ 2,167:
end program FileIO</syntaxhighlight>
=={{header|Frink}}==
Line 1,938 ⟶ 2,175:
w.close[]
</syntaxhighlight>
=={{header|GAP}}==
Line 2,020 ⟶ 2,194:
=={{header|GML}}==
<syntaxhighlight lang="gml">var file, str;
file = file_text_open_read("input.txt");
Line 2,384 ⟶ 2,557:
{{VI snippet}}<br/>
[[File:LabVIEW File IO.png]]
=={{header|Lang}}==
===Text-based===
{{libheader|lang-io-module}}
<syntaxhighlight lang="lang">
# Load the IO module
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">"
ln.loadModule(<pathToIO.lm>)
$fileIn = [[io]]::fp.openFile(input.txt)
$fileOut = [[io]]::fp.openFile(output.txt)
$text = [[io]]::fp.readFile($fileIn)
[[io]]::fp.writeFile($fileOut, $text)
[[io]]::fp.closeFile($fileIn)
[[io]]::fp.closeFile($fileOut)
</syntaxhighlight>
===Byte-based===
{{libheader|lang-io-module}}
<syntaxhighlight lang="lang">
# Load the IO module
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">"
ln.loadModule(<pathToIO.lm>)
$fileIn = [[io]]::fp.openFile(input.txt)
$fileOut = [[io]]::fp.openFile(output.txt)
$bytes = [[io]]::fp.readBytes($fileIn)
[[io]]::fp.writeBytes($fileOut, $bytes)
[[io]]::fp.closeFile($fileIn)
[[io]]::fp.closeFile($fileOut)
</syntaxhighlight>
=={{header|Lang5}}==
Line 2,393 ⟶ 2,601:
'output.txt 'input.txt copy-file</syntaxhighlight>
=={{header|Lingo}}==
Line 2,745 ⟶ 2,939:
i.close()
o.close()</syntaxhighlight>
=={{header|Nu}}==
<syntaxhighlight lang="nu">
let text = open "input.txt"
$text | save "output.txt"
</syntaxhighlight>
=={{header|Objeck}}==
Line 3,089 ⟶ 3,289:
Using an alternate cmdlet to write the file
<syntaxhighlight lang="powershell">Get-Content $PWD\input.txt | Set-Content $PWD\output.txt</syntaxhighlight>
=={{header|Python}}==
The following use of the standard libraries shutil.copyfile is to be preferred. (Current source code ensures that failure to open files raises appropriate exceptions, a restricted buffer is used to copy the files using binary mode, and any used file descriptors are always closed).
Line 3,252 ⟶ 3,411:
$in.close;
$out.close;</syntaxhighlight>
=={{header|Raven}}==
<syntaxhighlight lang="raven">'input.txt' read 'output.txt' write</syntaxhighlight>
=={{header|REBOL}}==
Line 3,402 ⟶ 3,508:
FileUtils.copy_file 'input.txt', 'output.txt'</syntaxhighlight>
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="runbasic">open "input.txt" for input as #in
fileLen = LOF(#in) 'Length Of File
Line 3,412 ⟶ 3,519:
close #out
end
</syntaxhighlight>
{{works with|Just BASIC}}
<syntaxhighlight lang="runbasic">open "input.txt" for input as #in
open "output.txt" for output as #out
fileLen = LOF(#in) 'Length Of File
Line 3,424 ⟶ 3,531:
=={{header|Rust}}==
<syntaxhighlight lang="rust">
let contents = std::fs::read("input.txt").expect("error reading input.txt");
std::fs::write("output.txt", contents).expect("error writing output.txt");
}
</syntaxhighlight>
Line 3,464 ⟶ 3,565:
process::exit(code);
}</syntaxhighlight>
=={{header|S-BASIC}}==
Surprisingly, S-BASIC has no EOF function, so we have to rely on error trapping to signal end of file. S-BASIC stores its error codes at 103H, and we can position a base-located variable there to retrieve it. The result is something of a kludge, but it works. Other S-BASIC preculiarities are explained by the comments.
<syntaxhighlight lang="BASIC">
comment
Preserve file channel #0 (the console) while declaring channels
#2 and #3 as sequential-access ASCII files.
end
files d, sa, sa
var s = string:255
based errcode = integer
base errcode at 103H
comment
CP/M expects upper case file names, but S-BASIC does not
automatically convert file name arguments to upper case, so we
have to do that ourself.
end
create "OUTPUT.TXT"
open #1,"INPUT.TXT"
open #2,"OUTPUT.TXT"
comment
S-BASIC allows alphanumeric line "numbers" (which are treated simply
as labels) as the target of GOTO and GOSUB statements, but the first
character must be a digit
end
on error goto 9done
rem - runtime error code 15 signals read past end of file
while errcode <> 15 do
begin
input3 #1; s
print #2; s
end
9done
close #1
close #2
end
</syntaxhighlight>
=={{header|Scala}}==
Line 3,585 ⟶ 3,729:
while output = input :s(while)
end</syntaxhighlight>
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "filecopy" )
@( description, "The job is to create a file called 'output.txt', and place in it" )
@( description, "the contents of the file 'input.txt'." )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/File_IO" );
pragma software_model( nonstandard );
pragma license( unrestricted );
procedure filecopy is
begin
if not files.is_readable( "input.txt" ) then
put_line( standard_error, source_info.source_location & ": input file is not readable" );
command_line.set_exit_status( 192 );
return;
end if;
-- With standard shell commands
cp input.txt output.txt;
-- Using built-in capabilities
pragma restriction( no_external_commands );
declare
inputfile : file_type;
outputfile : file_type;
begin
create( outputfile, out_file, "output.txt" );
open( inputfile, in_file, "input.txt" );
while not end_of_file( inputfile ) loop
put_line( outputfile, get_line( inputfile ) );
end loop;
close( inputfile ) @ ( outputfile );
end;
end filecopy;</syntaxhighlight>
=={{header|Standard ML}}==
===Reading the whole file at once as a string===
{{works with|SML/NJ|110.59}}
{{works with|Poly/ML|5.9.1}}
<syntaxhighlight lang="sml">
(* string -> string -> bool *)
fun copyFile from to =
let
val instream = TextIO.openIn from
Line 3,597 ⟶ 3,789:
in
true
end handle _ => false
===Binary mode using a buffer===
{{works with|Poly/ML|5.9.1}}
{{works with|SML/NJ|110.99.4}}
<syntaxhighlight lang="sml">
fun copyFile from to =
let
val instream = BinIO.openIn from
val outstream = BinIO.openOut to
fun aux () =
let
val buf = BinIO.inputN(instream, 1024)
in
if Word8Vector.length buf = 0
then ()
else (BinIO.output (outstream, buf); aux ())
end
in
(aux (); BinIO.closeIn instream; BinIO.closeOut outstream)
end
</syntaxhighlight>
=={{header|Stata}}==
Line 3,761 ⟶ 3,973:
fileio = ~command.files; &h.path.&h:= 'output.txt'!</syntaxhighlight>
=={{header|
<syntaxhighlight lang="Uxntal">|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1
|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1
|a0 @File1 &vector $2 &success $2 &stat $2 &delete $1 &append $1 &name $2 &length $2 &read $2 &write $2
|b0 @File2 &vector $2 &success $2 &stat $2 &delete $1 &append $1 &name $2 &length $2 &read $2 &write $2
|0100
;in-file .File1/name DEO2
;out-file .File2/name DEO2
&loop
#0100 .File1/length DEO2k POP
;buffer .File1/read DEO2
.File1/success DEI2
.File2/length DEO2k POP
;buffer .File2/write DEO2
EQU2 ?&loop
#80 .System/state DEO
BRK
@in-file "input.txt 00
@out-file "output.txt 00
@buffer $100</syntaxhighlight>
=={{header|Vedit macro language}}==
Line 3,800 ⟶ 4,006:
File_Save_As("output.txt", NOMSG)
Buf_Close(NOMSG) </syntaxhighlight>
=={{header|Wart}}==
Line 3,829 ⟶ 4,014:
=={{header|Wren}}==
<syntaxhighlight lang="
var contents = File.read("input.txt")
Line 3,871 ⟶ 4,056:
=={{header|Zig}}==
'''Works with:''' 0.10.x, 0.11.x, 0.12.0-dev.1357+10d03acdb
<syntaxhighlight lang="zig">const std = @import("std");
pub fn main() (error{OutOfMemory} || std.fs.File.OpenError || std.fs.File.ReadError || std.fs.File.WriteError)!void {
var
defer
const allocator = gpa.allocator();
var input_file = try cwd.openFile("input.txt", .{ .mode = .read_only });
var
defer output_file.close();
// Restrict input_file's size to "up to 10 MiB".
var input_file_content = try input_file.readToEndAlloc(allocator, 10 * 1024 * 1024);
defer allocator.free(input_file_content);
try output_file.writeAll(input_file_content);
return;
}</syntaxhighlight>
{{omit from|EasyLang}}
{{omit from|HTML}}
{{omit from|Order}}
|