Write entire file: Difference between revisions

Content added Content deleted
(Applesoft BASIC)
m (syntax highlighting fixup automation)
Line 14: Line 14:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>File(filename, ‘w’).write(string)</lang>
<syntaxhighlight lang="11l">File(filename, ‘w’).write(string)</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 writeFile64.s */
/* program writeFile64.s */
Line 109: Line 109:
.include "../includeARM64.inc"
.include "../includeARM64.inc"


</syntaxhighlight>
</lang>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>proc MAIN()
<syntaxhighlight lang="action!">proc MAIN()
open (1,"D:FILE.TXT",8,0)
open (1,"D:FILE.TXT",8,0)
printde(1,"My string")
printde(1,"My string")
close(1)
close(1)
return
return
</syntaxhighlight>
</lang>


=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;


procedure Write_Whole_File is
procedure Write_Whole_File is
Line 139: Line 139:
Close (F);
Close (F);
end Write_Whole_File;
end Write_Whole_File;
</syntaxhighlight>
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>IF FILE output;
<syntaxhighlight lang="algol68">IF FILE output;
STRING output file name = "output.txt";
STRING output file name = "output.txt";
open( output, output file name, stand out channel ) = 0
open( output, output file name, stand out channel ) = 0
Line 152: Line 152:
# unable to open the output file #
# unable to open the output file #
print( ( "Cannot open ", output file name, newline ) )
print( ( "Cannot open ", output file name, newline ) )
FI</lang>
FI</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>contents: "Hello World!"
<syntaxhighlight lang="rebol">contents: "Hello World!"
write "output.txt" contents</lang>
write "output.txt" contents</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>file := FileOpen("test.txt", "w")
<syntaxhighlight lang="autohotkey">file := FileOpen("test.txt", "w")
file.Write("this is a test string")
file.Write("this is a test string")
file.Close()</lang>
file.Close()</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f WRITE_ENTIRE_FILE.AWK
# syntax: GAWK -f WRITE_ENTIRE_FILE.AWK
BEGIN {
BEGIN {
Line 172: Line 172:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>


=={{header|BaCon}}==
=={{header|BaCon}}==
String:
String:
<lang freebasic>SAVE s$ TO filename$</lang>
<syntaxhighlight lang="freebasic">SAVE s$ TO filename$</syntaxhighlight>


Binary:
Binary:
<lang freebasic>BSAVE mem TO filename$ SIZE n</lang>
<syntaxhighlight lang="freebasic">BSAVE mem TO filename$ SIZE n</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang gwbasic> 10 D$ = CHR$ (4)
<syntaxhighlight lang="gwbasic"> 10 D$ = CHR$ (4)
20 F$ = "OUTPUT.TXT"
20 F$ = "OUTPUT.TXT"
30 PRINT D$"OPEN"F$
30 PRINT D$"OPEN"F$
Line 191: Line 191:
70 PRINT D$"WRITE"F$
70 PRINT D$"WRITE"F$
80 PRINT "THIS STRING IS TO BE WRITTEN TO THE FILE"
80 PRINT "THIS STRING IS TO BE WRITTEN TO THE FILE"
90 PRINT D$"CLOSE"F$</lang>
90 PRINT D$"CLOSE"F$</syntaxhighlight>
==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang freebasic>f = freefile
<syntaxhighlight lang="freebasic">f = freefile
open f, "output.txt"
open f, "output.txt"
write f, "This string is to be written to the file"
write f, "This string is to be written to the file"
close f</lang>
close f</syntaxhighlight>


==={{header|QBasic}}===
==={{header|QBasic}}===
{{works with|FreeBASIC}}
{{works with|FreeBASIC}}
<lang QBasic>f = FREEFILE
<syntaxhighlight lang="qbasic">f = FREEFILE
OPEN "output.txt" FOR OUTPUT AS #f
OPEN "output.txt" FOR OUTPUT AS #f
PRINT #f, "This string is to be written to the file"
PRINT #f, "This string is to be written to the file"
CLOSE #</lang>
CLOSE #</syntaxhighlight>


==={{header|Run BASIC}}===
==={{header|Run BASIC}}===
{{works with|QBasic}}
{{works with|QBasic}}
{{works with|FreeBASIC}}
{{works with|FreeBASIC}}
<lang runbasic>open "output.txt" for output as #1
<syntaxhighlight lang="runbasic">open "output.txt" for output as #1
print #1, "This string is to be written to the file"
print #1, "This string is to be written to the file"
close #1</lang>
close #1</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang qbasic>OPEN #1: NAME "output.txt", CREATE NEWOLD
<syntaxhighlight lang="qbasic">OPEN #1: NAME "output.txt", CREATE NEWOLD
PRINT #1: "This string is to be written to the file"
PRINT #1: "This string is to be written to the file"
CLOSE #1
CLOSE #1
END</lang>
END</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic>file% = OPENOUT filename$
<syntaxhighlight lang="bbcbasic">file% = OPENOUT filename$
PRINT#file%, text$
PRINT#file%, text$
CLOSE#file%</lang>
CLOSE#file%</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>put$("(Over)write a file so that it contains a string.",file,NEW)</lang>
<syntaxhighlight lang="bracmat">put$("(Over)write a file so that it contains a string.",file,NEW)</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==


=== Dirty solution ===
=== Dirty solution ===
<syntaxhighlight lang="c">/*
<lang C>/*
* Write Entire File -- RossetaCode -- dirty hackish solution
* Write Entire File -- RossetaCode -- dirty hackish solution
*/
*/
Line 240: Line 240:
freopen("sample.txt","wb",stdout));
freopen("sample.txt","wb",stdout));
}
}
</syntaxhighlight>
</lang>
=== Standard function fwrite() ===
=== Standard function fwrite() ===
<syntaxhighlight lang="c">/*
<lang C>/*
* Write Entire File -- RossetaCode -- ASCII version with BUFFERED files
* Write Entire File -- RossetaCode -- ASCII version with BUFFERED files
*/
*/
Line 339: Line 339:
return EXIT_FAILURE;
return EXIT_FAILURE;
}
}
</syntaxhighlight>
</lang>
=== POSIX function write() ===
=== POSIX function write() ===
<syntaxhighlight lang="c">/*
<lang C>/*
* Write Entire File -- RossetaCode -- plain POSIX write() from io.h
* Write Entire File -- RossetaCode -- plain POSIX write() from io.h
*/
*/
Line 407: Line 407:
return 1;
return 1;
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>System.IO.File.WriteAllText("filename.txt", "This file contains a string.");</lang>
<syntaxhighlight lang="csharp">System.IO.File.WriteAllText("filename.txt", "This file contains a string.");</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <fstream>
<syntaxhighlight lang="cpp">#include <fstream>
using namespace std;
using namespace std;


Line 422: Line 422:
file.close();
file.close();
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(spit "file.txt" "this is a string")</lang>
<syntaxhighlight lang="clojure">(spit "file.txt" "this is a string")</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. Overwrite.
PROGRAM-ID. Overwrite.
Line 471: Line 471:
END-PROGRAM.
END-PROGRAM.
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(with-open-file (str "filename.txt"
<syntaxhighlight lang="lisp">(with-open-file (str "filename.txt"
:direction :output
:direction :output
:if-exists :supersede
:if-exists :supersede
:if-does-not-exist :create)
:if-does-not-exist :create)
(format str "File content...~%"))</lang>
(format str "File content...~%"))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang D>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main() {
void main() {
auto file = File("new.txt", "wb");
auto file = File("new.txt", "wb");
file.writeln("Hello World!");
file.writeln("Hello World!");
}</lang>
}</syntaxhighlight>
=={{header|Delphi}}==
=={{header|Delphi}}==
{{libheader| System.IoUtils}}
{{libheader| System.IoUtils}}
{{Trans|C#}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Write_entire_file;
program Write_entire_file;


Line 500: Line 500:
begin
begin
TFile.WriteAllText('filename.txt', 'This file contains a string.');
TFile.WriteAllText('filename.txt', 'This file contains a string.');
end.</lang>
end.</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import system'io;
<syntaxhighlight lang="elena">import system'io;
public program()
public program()
{
{
File.assign("filename.txt").saveContent("This file contains a string.")
File.assign("filename.txt").saveContent("This file contains a string.")
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>File.write("file.txt", string)</lang>
<syntaxhighlight lang="elixir">File.write("file.txt", string)</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>System.IO.File.WriteAllText("filename.txt", "This file contains a string.")</lang>
<syntaxhighlight lang="fsharp">System.IO.File.WriteAllText("filename.txt", "This file contains a string.")</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: io.encodings.utf8 io.files ;
<syntaxhighlight lang="factor">USING: io.encodings.utf8 io.files ;
"this is a string" "file.txt" utf8 set-file-contents</lang>
"this is a string" "file.txt" utf8 set-file-contents</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Where F is an integer with a value such as 10 (these days not being 5, standard input, nor 6, standard output), the I/O unit number. "REPLACE" means create the file if it does not exist, otherwise delete the existing file and create a new one of that name. The WRITE statement may present a single (large?) item, a list of items, and possibly there would be a series of WRITE statements if there is no need to do the deed via one WRITE only.
Where F is an integer with a value such as 10 (these days not being 5, standard input, nor 6, standard output), the I/O unit number. "REPLACE" means create the file if it does not exist, otherwise delete the existing file and create a new one of that name. The WRITE statement may present a single (large?) item, a list of items, and possibly there would be a series of WRITE statements if there is no need to do the deed via one WRITE only.
<lang Fortran> OPEN (F,FILE="SomeFileName.txt",STATUS="REPLACE")
<syntaxhighlight lang="fortran"> OPEN (F,FILE="SomeFileName.txt",STATUS="REPLACE")
WRITE (F,*) "Whatever you like."
WRITE (F,*) "Whatever you like."
WRITE (F) BIGARRAY</lang>
WRITE (F) BIGARRAY</syntaxhighlight>
Earlier Fortran might have other predefined unit numbers, for a card punch, paper tape, lineprinter, and so on, according to the installation. For a disc file, there may be no facility to name the file within Fortran itself as in the example OPEN statement because there may be no OPEN statement. Fortran IV used a DEFINE FILE statement, for example, which specified the record length and number of records in the file. As constants. File naming would instead be done by commands to the operating system when the prog. is started, as with the DD statement of JCL (Job Control Language) of IBM mainframes, and this would have its own jargon for NEW, OLD, REPLACE and what to do when the step finishes: DISP=KEEP, perhaps.
Earlier Fortran might have other predefined unit numbers, for a card punch, paper tape, lineprinter, and so on, according to the installation. For a disc file, there may be no facility to name the file within Fortran itself as in the example OPEN statement because there may be no OPEN statement. Fortran IV used a DEFINE FILE statement, for example, which specified the record length and number of records in the file. As constants. File naming would instead be done by commands to the operating system when the prog. is started, as with the DD statement of JCL (Job Control Language) of IBM mainframes, and this would have its own jargon for NEW, OLD, REPLACE and what to do when the step finishes: DISP=KEEP, perhaps.


Line 540: Line 540:
=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
''See also: [[#Pascal]]''
''See also: [[#Pascal]]''
<lang Pascal>program overwriteFile(input, output, stdErr);
<syntaxhighlight lang="pascal">program overwriteFile(input, output, stdErr);
{$mode objFPC} // for exception treatment
{$mode objFPC} // for exception treatment
uses
uses
Line 559: Line 559:
close(FD);
close(FD);
end;
end;
end.</lang>
end.</syntaxhighlight>


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


Open "output.txt" For Output As #1
Open "output.txt" For Output As #1
Print #1, "This is a string"
Print #1, "This is a string"
Close #1</lang>
Close #1</syntaxhighlight>


=={{header|Frink}}==
=={{header|Frink}}==
<syntaxhighlight lang="frink">
<lang Frink>
w = new Writer["test.txt"]
w = new Writer["test.txt"]
w.print["I am the captain now."]
w.print["I am the captain now."]
w.close[]
w.close[]
</syntaxhighlight>
</lang>


=={{header|Gambas}}==
=={{header|Gambas}}==
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()


File.Save(User.home &/ "test.txt", "(Over)write a file so that it contains a string.")
File.Save(User.home &/ "test.txt", "(Over)write a file so that it contains a string.")


End</lang>
End</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang Go>import "io/ioutil"
<syntaxhighlight lang="go">import "io/ioutil"


func main() {
func main() {
ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang Groovy> new File("myFile.txt").text = """a big string
<syntaxhighlight lang="groovy"> new File("myFile.txt").text = """a big string
that can be
that can be
splitted over lines
splitted over lines
"""
"""
</syntaxhighlight>
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang Haskell>main :: IO ( )
<syntaxhighlight lang="haskell">main :: IO ( )
main = do
main = do
putStrLn "Enter a string!"
putStrLn "Enter a string!"
Line 603: Line 603:
putStrLn "Where do you want to store this string ?"
putStrLn "Where do you want to store this string ?"
myFile <- getLine
myFile <- getLine
appendFile myFile str</lang>
appendFile myFile str</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang J> characters fwrite filename</lang>
<syntaxhighlight lang="j"> characters fwrite filename</syntaxhighlight>


or,
or,


<lang J> characters 1!:2<filename</lang>
<syntaxhighlight lang="j"> characters 1!:2<filename</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.io.*;
<syntaxhighlight lang="java">import java.io.*;


public class Test {
public class Test {
Line 622: Line 622:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>function writeFile(filename, data)
<syntaxhighlight lang="julia">function writeFile(filename, data)
f = open(filename, "w")
f = open(filename, "w")
write(f, data)
write(f, data)
Line 631: Line 631:
end
end


writeFile("test.txt", "Hi there.")</lang>
writeFile("test.txt", "Hi there.")</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


import java.io.File
import java.io.File
Line 641: Line 641:
val text = "empty vessels make most noise"
val text = "empty vessels make most noise"
File("output.txt").writeText(text)
File("output.txt").writeText(text)
}</lang>
}</syntaxhighlight>


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


=={{header|LiveCode}}==
=={{header|LiveCode}}==
This will create a file "TestFile.txt" or overwrite it if it already exists. This is the shortest method for file I/O in LiveCode, but not the only method.
This will create a file "TestFile.txt" or overwrite it if it already exists. This is the shortest method for file I/O in LiveCode, but not the only method.
<syntaxhighlight lang="livecode">
<lang LiveCode>
put "this is a string" into URL "file:~/Desktop/TestFile.txt"
put "this is a string" into URL "file:~/Desktop/TestFile.txt"
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>function writeFile (filename, data)
<syntaxhighlight lang="lua">function writeFile (filename, data)
local f = io.open(filename, 'w')
local f = io.open(filename, 'w')
f:write(data)
f:write(data)
Line 678: Line 678:
end
end


writeFile("stringFile.txt", "Mmm... stringy.")</lang>
writeFile("stringFile.txt", "Mmm... stringy.")</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>Export("directory/filename.txt", string);</lang>
<syntaxhighlight lang="maple">Export("directory/filename.txt", string);</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Export["filename.txt","contents string"]</lang>
<syntaxhighlight lang="mathematica">Export["filename.txt","contents string"]</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>import Nanoquery.IO
<syntaxhighlight lang="nanoquery">import Nanoquery.IO


new(File, fname).create().write(string)</lang>
new(File, fname).create().write(string)</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>
<syntaxhighlight lang="nim">
writeFile("filename.txt", "An arbitrary string")
writeFile("filename.txt", "An arbitrary string")
</syntaxhighlight>
</lang>


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


class WriteFile {
class WriteFile {
Line 707: Line 707:
writer→WriteString("this is a test string");
writer→WriteString("this is a test string");
}
}
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>let write_file filename s =
<syntaxhighlight lang="ocaml">let write_file filename s =
let oc = open_out filename in
let oc = open_out filename in
output_string oc s;
output_string oc s;
Line 720: Line 720:
let filename = "test.txt" in
let filename = "test.txt" in
let s = String.init 26 (fun i -> char_of_int (i + int_of_char 'A')) in
let s = String.init 26 (fun i -> char_of_int (i + int_of_char 'A')) in
write_file filename s</lang>
write_file filename s</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 726: Line 726:


In Standard Pascal, a list of identifiers in the program header sets up a list of file handlers.
In Standard Pascal, a list of identifiers in the program header sets up a list of file handlers.
<lang Pascal>{$ifDef FPC}{$mode ISO}{$endIf}
<syntaxhighlight lang="pascal">{$ifDef FPC}{$mode ISO}{$endIf}
program overwriteFile(FD);
program overwriteFile(FD);
begin
begin
writeLn(FD, 'Whasup?');
writeLn(FD, 'Whasup?');
close(FD);
close(FD);
end.</lang>
end.</syntaxhighlight>
In some environments, it is the caller’s sole responsibility to invoke the program properly.
In some environments, it is the caller’s sole responsibility to invoke the program properly.
I. e., the program above could be invoked on a Bourne-again shell in this fashion:
I. e., the program above could be invoked on a Bourne-again shell in this fashion:
<lang bash>./overwriteFile >&- <&- 0>/tmp/foo # open file descriptor with index 0 for writing</lang>
<syntaxhighlight lang="bash">./overwriteFile >&- <&- 0>/tmp/foo # open file descriptor with index 0 for writing</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
Line 740: Line 740:
The modern recommended way, is to use one of these CPAN modules:
The modern recommended way, is to use one of these CPAN modules:


<lang perl>use File::Slurper 'write_text';
<syntaxhighlight lang="perl">use File::Slurper 'write_text';
write_text($filename, $data);</lang>
write_text($filename, $data);</syntaxhighlight>


<lang perl>use Path::Tiny;
<syntaxhighlight lang="perl">use Path::Tiny;
path($filename)->spew_utf8($data);</lang>
path($filename)->spew_utf8($data);</syntaxhighlight>


Traditional way, in case using CPAN modules is not an option:
Traditional way, in case using CPAN modules is not an option:


<lang perl>open my $fh, '>:encoding(UTF-8)', $filename or die "Could not open '$filename': $!";
<syntaxhighlight lang="perl">open my $fh, '>:encoding(UTF-8)', $filename or die "Could not open '$filename': $!";
print $fh $data;
print $fh $data;
close $fh;</lang>
close $fh;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">write_lines</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"file.txt"</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"line 1\nline 2"</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">write_lines</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"file.txt"</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"line 1\nline 2"</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"error"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"error"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
lines can also be {"line 1","line 2"} (note that a \n is appended to each line) or other multiline/triplequoted text.<br>
lines can also be {"line 1","line 2"} (note that a \n is appended to each line) or other multiline/triplequoted text.<br>
See also open(), puts(), printf(), (neither of which add any \n), close(), temp_file(), create_directory()...
See also open(), puts(), printf(), (neither of which add any \n), close(), temp_file(), create_directory()...


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>file_put_contents($filename, $data)</lang>
<syntaxhighlight lang="php">file_put_contents($filename, $data)</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(out "file.txt"
<syntaxhighlight lang="picolisp">(out "file.txt"
(prinl "My string") )</lang>
(prinl "My string") )</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang Pike>Stdio.write_file("file.txt", "My string");</lang>
<syntaxhighlight lang="pike">Stdio.write_file("file.txt", "My string");</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Writes all running process details to a file in the current directory.
Writes all running process details to a file in the current directory.
<lang powershell>
<syntaxhighlight lang="powershell">
Get-Process | Out-File -FilePath .\ProcessList.txt
Get-Process | Out-File -FilePath .\ProcessList.txt
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
EnableExplicit
EnableExplicit


Line 795: Line 795:
CloseConsole()
CloseConsole()
EndIf
EndIf
</syntaxhighlight>
</lang>


{{out|Output (contents of 'output.exe')}}
{{out|Output (contents of 'output.exe')}}
Line 803: Line 803:


=={{header|Python}}==
=={{header|Python}}==
<lang python>with open(filename, 'w') as f:
<syntaxhighlight lang="python">with open(filename, 'w') as f:
f.write(data)</lang>
f.write(data)</syntaxhighlight>


Starting in Python 3.4, we can use <code>pathlib</code> to reduce boilerplate:
Starting in Python 3.4, we can use <code>pathlib</code> to reduce boilerplate:


<lang python>from pathlib import Path
<syntaxhighlight lang="python">from pathlib import Path


Path(filename).write_text(any_string)
Path(filename).write_text(any_string)
Path(filename).write_bytes(any_binary_data)</lang>
Path(filename).write_bytes(any_binary_data)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
This only replaces the file if it exists, otherwise it writes a new file. Use <tt>'truncate</tt> to overwrite the new contents into the existing file.
This only replaces the file if it exists, otherwise it writes a new file. Use <tt>'truncate</tt> to overwrite the new contents into the existing file.
<lang racket>#lang racket/base
<syntaxhighlight lang="racket">#lang racket/base
(with-output-to-file "/tmp/out-file.txt" #:exists 'replace
(with-output-to-file "/tmp/out-file.txt" #:exists 'replace
(lambda () (display "characters")))</lang>
(lambda () (display "characters")))</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)


<lang perl6>spurt 'path/to/file', $file-data;</lang>
<syntaxhighlight lang="raku" line>spurt 'path/to/file', $file-data;</syntaxhighlight>
or
or
<lang perl6>'path/to/file'.IO.spurt: $file-data;</lang>
<syntaxhighlight lang="raku" line>'path/to/file'.IO.spurt: $file-data;</syntaxhighlight>


=={{header|RATFOR}}==
=={{header|RATFOR}}==
<syntaxhighlight lang="ratfor">
<lang RATFOR>


# Program to overwrite an existing file
# Program to overwrite an existing file
Line 837: Line 837:


end
end
</syntaxhighlight>
</lang>




=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<lang rexx>
<syntaxhighlight lang="rexx">
/*REXX*/
/*REXX*/


Line 850: Line 850:
Call charout of,s
Call charout of,s
Call lineout of
Call lineout of
Say chars(of) length(s) </lang>
Say chars(of) length(s) </syntaxhighlight>
{{out}}
{{out}}
<pre>100000 100000</pre>
<pre>100000 100000</pre>
Line 861: Line 861:
===version 2===
===version 2===
This REXX version doesn't depend on any (operating system) host commands.
This REXX version doesn't depend on any (operating system) host commands.
<lang rexx>/*REXX program writes an entire file with a single write (a long text record). */
<syntaxhighlight lang="rexx">/*REXX program writes an entire file with a single write (a long text record). */
oFID= 'OUTPUT.DAT' /*name of the output file to be used. */
oFID= 'OUTPUT.DAT' /*name of the output file to be used. */
/* [↓] 50 bytes, including the fences.*/
/* [↓] 50 bytes, including the fences.*/
Line 868: Line 868:
call charout oFID, copies($,1000), 1 /*write the longish text to the file. */
call charout oFID, copies($,1000), 1 /*write the longish text to the file. */
/* [↑] the "1" writes text ──► rec #1*/
/* [↑] the "1" writes text ──► rec #1*/
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>
<br><br>
<br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
write("myfile.txt","Hello, World!")
write("myfile.txt","Hello, World!")
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
The file is closed at the end of the block.
The file is closed at the end of the block.
<lang ruby>open(fname, 'w'){|f| f.write(str) }</lang>
<syntaxhighlight lang="ruby">open(fname, 'w'){|f| f.write(str) }</syntaxhighlight>


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


Line 889: Line 889:
write!(file, "{}", data)?;
write!(file, "{}", data)?;
Ok(())
Ok(())
}</lang>
}</syntaxhighlight>


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


object Main extends App {
object Main extends App {
Line 901: Line 901:
" frictional radial anti-stabilizer vectronize from the flumberboozle to the XKG virtual port?")
" frictional radial anti-stabilizer vectronize from the flumberboozle to the XKG virtual port?")
close()}
close()}
}</lang>
}</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>put "New String" into file "~/Desktop/myFile.txt"</lang>
<syntaxhighlight lang="sensetalk">put "New String" into file "~/Desktop/myFile.txt"</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
With error handling:
With error handling:
<lang ruby>var file = File(__FILE__)
<syntaxhighlight lang="ruby">var file = File(__FILE__)
file.open_w(\var fh, \var err) || die "Can't open #{file}: #{err}"
file.open_w(\var fh, \var err) || die "Can't open #{file}: #{err}"
fh.print("Hello world!") || die "Can't write to #{file}: #{$!}"</lang>
fh.print("Hello world!") || die "Can't write to #{file}: #{$!}"</syntaxhighlight>
Without error handling:
Without error handling:
<lang ruby>File(__FILE__).open_w.print("Hello world!")</lang>
<syntaxhighlight lang="ruby">File(__FILE__).open_w.print("Hello world!")</syntaxhighlight>
=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with | Smalltalk/X}}
{{works with | Smalltalk/X}}
<lang smalltalk>'file.txt' asFilename contents:'Hello World'</lang>
<syntaxhighlight lang="smalltalk">'file.txt' asFilename contents:'Hello World'</syntaxhighlight>


=={{header|SPL}}==
=={{header|SPL}}==
<lang spl>#.writetext("file.txt","This is the string")</lang>
<syntaxhighlight lang="spl">#.writetext("file.txt","This is the string")</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun writeFile (path, str) =
<syntaxhighlight lang="sml">fun writeFile (path, str) =
(fn strm =>
(fn strm =>
TextIO.output (strm, str) before TextIO.closeOut strm) (TextIO.openOut path)</lang>
TextIO.output (strm, str) before TextIO.closeOut strm) (TextIO.openOut path)</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==


<lang Tcl>proc writefile {filename data} {
<syntaxhighlight lang="tcl">proc writefile {filename data} {
set fd [open $filename w] ;# truncate if exists, else create
set fd [open $filename w] ;# truncate if exists, else create
try {
try {
Line 934: Line 934:
close $fd
close $fd
}
}
}</lang>
}</syntaxhighlight>


A more elaborate version of this procedure might take optional arguments to pass to <tt>fconfigure</tt> (such as encoding) or <tt>open</tt> (such as permissions).
A more elaborate version of this procedure might take optional arguments to pass to <tt>fconfigure</tt> (such as encoding) or <tt>open</tt> (such as permissions).


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
content="new text that will overwrite content of myfile"
content="new text that will overwrite content of myfile"
Line 948: Line 948:
IF (status=="CREATE") ERROR/STOP CREATE ("myfile",seq-o,-std-)
IF (status=="CREATE") ERROR/STOP CREATE ("myfile",seq-o,-std-)
ENDLOOP
ENDLOOP
</syntaxhighlight>
</lang>


=={{header|VBA}}==
=={{header|VBA}}==


<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
Option Explicit


Line 967: Line 967:
Print #1, Text
Print #1, Text
Close #Nb
Close #Nb
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
Text file created or overwritten in the same folder as the script.
Text file created or overwritten in the same folder as the script.
<syntaxhighlight lang="vb">
<lang vb>
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFSO = CreateObject("Scripting.FileSystemObject")


Line 984: Line 984:


Set objFSO = Nothing
Set objFSO = Nothing
</syntaxhighlight>
</lang>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Module Module1
<syntaxhighlight lang="vbnet">Module Module1


Sub Main()
Sub Main()
Line 995: Line 995:


End Module
End Module
</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
The easiest way to overwrite a file in Wren is to 'create' it again which truncates the existing contents.
The easiest way to overwrite a file in Wren is to 'create' it again which truncates the existing contents.
<lang ecmascript>import "io" for File
<syntaxhighlight lang="ecmascript">import "io" for File


// create a text file
// create a text file
Line 1,015: Line 1,015:


// check it worked
// check it worked
System.print(File.read("hello.txt"))</lang>
System.print(File.read("hello.txt"))</syntaxhighlight>


{{out}}
{{out}}
Line 1,024: Line 1,024:


=={{header|XLISP}}==
=={{header|XLISP}}==
<lang scheme>(define n (open-output-file "example.txt"))
<syntaxhighlight lang="scheme">(define n (open-output-file "example.txt"))
(write "(Over)write a file so that it contains a string." n)
(write "(Over)write a file so that it contains a string." n)
(close-output-port n)</lang>
(close-output-port n)</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>[FSet(FOpen("output.txt", 1), ^o);
<syntaxhighlight lang="xpl0">[FSet(FOpen("output.txt", 1), ^o);
Text(3, "This is a string.");
Text(3, "This is a string.");
]</lang>
]</syntaxhighlight>


=={{header|Xtend}}==
=={{header|Xtend}}==
<lang java>
<syntaxhighlight lang="java">
package com.rosetta.example
package com.rosetta.example


Line 1,047: Line 1,047:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>open "output.txt" for writing as #1
<syntaxhighlight lang="yabasic">open "output.txt" for writing as #1
print #1 "This is a string"
print #1 "This is a string"
close #1</lang>
close #1</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl> // write returns bytes written, GC will close the file (eventually)
<syntaxhighlight lang="zkl"> // write returns bytes written, GC will close the file (eventually)
File("foo","wb").write("this is a test",1,2,3); //-->17
File("foo","wb").write("this is a test",1,2,3); //-->17


f:=File("bar",wb");
f:=File("bar",wb");
data.pump(f,g); // use g to process data as it is written to file
data.pump(f,g); // use g to process data as it is written to file
f.close(); // don't wait for GC</lang>
f.close(); // don't wait for GC</syntaxhighlight>