Write entire file: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(add Standard ML)
m (→‎{{header|Wren}}: Changed to Wren S/H)
(23 intermediate revisions by 16 users not shown)
Line 12:
The reverse of [[Read entire file]]—for when you want to update or create a file which you would read in its entirety all at once.
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">File(filename, ‘w’).write(string)</syntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program writeFile64.s */
Line 106 ⟶ 109:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">proc MAIN()
open (1,"D:FILE.TXT",8,0)
printde(1,"My string")
close(1)
return
</syntaxhighlight>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Write_Whole_File is
Line 128 ⟶ 139:
Close (F);
end Write_Whole_File;
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">IF FILE output;
STRING output file name = "output.txt";
open( output, output file name, stand out channel ) = 0
Line 141 ⟶ 152:
# unable to open the output file #
print( ( "Cannot open ", output file name, newline ) )
FI</langsyntaxhighlight>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">contents: "Hello World!"
write "output.txt" contents</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">file := FileOpen("test.txt", "w")
file.Write("this is a test string")
file.Close()</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f WRITE_ENTIRE_FILE.AWK
BEGIN {
Line 161 ⟶ 172:
exit(0)
}
</syntaxhighlight>
</lang>
 
=={{header|BaCon}}==
String:
<syntaxhighlight lang ="freebasic">SAVE s$ TO filename$</langsyntaxhighlight>
 
Binary:
<langsyntaxhighlight lang="freebasic">BSAVE mem TO filename$ SIZE n</langsyntaxhighlight>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic"> 10 D$ = CHR$ (4)
20 F$ = "OUTPUT.TXT"
30 PRINT D$"OPEN"F$
40 PRINT D$"CLOSE"F$
50 PRINT D$"DELETE"F$
60 PRINT D$"OPEN"F$
70 PRINT D$"WRITE"F$
80 PRINT "THIS STRING IS TO BE WRITTEN TO THE FILE"
90 PRINT D$"CLOSE"F$</syntaxhighlight>
==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">f = freefile
open f, "output.txt"
write f, "This string is to be written to the file"
close f</syntaxhighlight>
 
==={{header|QBasic}}===
{{works with|FreeBASIC}}
<syntaxhighlight lang="qbasic">f = FREEFILE
OPEN "output.txt" FOR OUTPUT AS #f
PRINT #f, "This string is to be written to the file"
CLOSE #</syntaxhighlight>
 
==={{header|Run BASIC}}===
{{works with|QBasic}}
{{works with|FreeBASIC}}
<syntaxhighlight lang="runbasic">open "output.txt" for output as #1
print #1, "This string is to be written to the file"
close #1</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">OPEN #1: NAME "output.txt", CREATE NEWOLD
PRINT #1: "This string is to be written to the file"
CLOSE #1
END</syntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic">file% = OPENOUT filename$
PRINT#file%, text$
CLOSE#file%</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">put$("(Over)write a file so that it contains a string.",file,NEW)</langsyntaxhighlight>
 
=={{header|C}}==
 
=== Dirty solution ===
<syntaxhighlight lang="c">/*
<lang C>/*
* Write Entire File -- RossetaCode -- dirty hackish solution
*/
Line 192 ⟶ 240:
freopen("sample.txt","wb",stdout));
}
</syntaxhighlight>
</lang>
=== Standard function fwrite() ===
<syntaxhighlight lang="c">/*
<lang C>/*
* Write Entire File -- RossetaCode -- ASCII version with BUFFERED files
*/
Line 291 ⟶ 339:
return EXIT_FAILURE;
}
</syntaxhighlight>
</lang>
=== POSIX function write() ===
<syntaxhighlight lang="c">/*
<lang C>/*
* Write Entire File -- RossetaCode -- plain POSIX write() from io.h
*/
Line 359 ⟶ 407:
return 1;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">System.IO.File.WriteAllText("filename.txt", "This file contains a string.");</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <fstream>
using namespace std;
 
Line 374 ⟶ 422:
file.close();
return 0;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(spit "file.txt" "this is a string")</langsyntaxhighlight>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. Overwrite.
AUTHOR. Bill Gunshannon.
INSTALLATION. Home.
DATE-WRITTEN. 31 December 2021.
************************************************************
** Program Abstract:
** Simple COBOL task. Open file for output. Write
** data to file. Close file. Done...
************************************************************
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT File-Name ASSIGN TO "File.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD File-Name
DATA RECORD IS Record-Name.
01 Record-Name.
02 Field1 PIC X(80).
WORKING-STORAGE SECTION.
01 New-Val PIC X(80)
VALUE 'Hello World'.
PROCEDURE DIVISION.
Main-Program.
OPEN OUTPUT File-Name.
WRITE Record-Name FROM New-Val.
CLOSE File-Name.
STOP RUN.
END-PROGRAM.
</syntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(with-open-file (str "filename.txt"
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(format str "File content...~%"))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
auto file = File("new.txt", "wb");
file.writeln("Hello World!");
}</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.IoUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Write_entire_file;
 
{$APPTYPE CONSOLE}
 
uses
System.IoUtils;
 
begin
TFile.WriteAllText('filename.txt', 'This file contains a string.');
end.</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x :
<langsyntaxhighlight lang="elena">import system'io;
public program()
{
File.assign("filename.txt").saveContent("This file contains a string.")
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">File.write("file.txt", string)</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">System.IO.File.WriteAllText("filename.txt", "This file contains a string.")</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: io.encodings.utf8 io.files ;
"this is a string" "file.txt" utf8 set-file-contents</langsyntaxhighlight>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">
: >file ( string len filename len -- )
w/o create-file throw dup >r write-file throw r> close-file throw ;
 
s" This is a string." s" file.txt" >file
</syntaxhighlight>
=={{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.
<langsyntaxhighlight Fortranlang="fortran"> OPEN (F,FILE="SomeFileName.txt",STATUS="REPLACE")
WRITE (F,*) "Whatever you like."
WRITE (F) BIGARRAY</langsyntaxhighlight>
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 432 ⟶ 547:
=={{header|Free Pascal}}==
''See also: [[#Pascal]]''
<langsyntaxhighlight Pascallang="pascal">program overwriteFile(input, output, stdErr);
{$mode objFPC} // for exception treatment
uses
Line 451 ⟶ 566:
close(FD);
end;
end.</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Open "output.txt" For Output As #1
Print #1, "This is a string"
Close #1</langsyntaxhighlight>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">
<lang Frink>
w = new Writer["test.txt"]
w.print["I am the captain now."]
w.close[]
</syntaxhighlight>
</lang>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
void local fn SaveFile
CFStringRef fileString = @"The quick brown fox jumped over the lazy dog's back."
CFURLRef url = savepanel 1, @"Choose location to save file.", @"txt", @"Untitled", @"Save"
if (url)
fn StringWriteToURL( fileString, url, YES, NSUTF8StringEncoding, NULL )
else
// User canceled
end if
end fn
 
fn SaveFile
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:Write entire file.png]]
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">Public Sub Main()
 
File.Save(User.home &/ "test.txt", "(Over)write a file so that it contains a string.")
 
End</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight Golang="go">import "io/ioutil"
 
func main() {
ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight Groovylang="groovy"> new File("myFile.txt").text = """a big string
that can be
splitted over lines
"""
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">main :: IO ( )
main = do
putStrLn "Enter a string!"
Line 495 ⟶ 630:
putStrLn "Where do you want to store this string ?"
myFile <- getLine
appendFile myFile str</langsyntaxhighlight>
 
=={{header|J}}==
<syntaxhighlight lang J="j"> characters fwrite filename</langsyntaxhighlight>
 
or,
 
<syntaxhighlight lang J="j"> characters 1!:2<filename</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.io.*;
 
public class Test {
Line 514 ⟶ 649:
}
}
}</langsyntaxhighlight>
 
===Using Java 11===
<syntaxhighlight lang="java">
 
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
 
public final class WriteEntireFile {
 
public static void main(String[] aArgs) throws IOException {
String contents = "Hello World";
String filePath = "output.txt";
Files.write(Path.of(filePath), contents.getBytes(), StandardOpenOption.CREATE);
}
 
}
</syntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">function writeFile(filename, data)
f = open(filename, "w")
write(f, data)
Line 523 ⟶ 678:
end
 
writeFile("test.txt", "Hi there.")</langsyntaxhighlight>
 
=={{header|K}}==
{{works with|ngn/k}}
<syntaxhighlight lang=K>"example.txt" 0:"example file contents"</syntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.io.File
Line 533 ⟶ 692:
val text = "empty vessels make most noise"
File("output.txt").writeText(text)
}</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">----------------------------------------
-- Saves string as file
-- @param {string} tFile
Line 555 ⟶ 714:
fp.closeFile()
return true
end</langsyntaxhighlight>
 
=={{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.
<syntaxhighlight lang="livecode">
<lang LiveCode>
put "this is a string" into URL "file:~/Desktop/TestFile.txt"
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function writeFile (filename, data)
local f = io.open(filename, 'w')
f:write(data)
Line 570 ⟶ 729:
end
 
writeFile("stringFile.txt", "Mmm... stringy.")</langsyntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">Export("directory/filename.txt", string);</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Export["filename.txt","contents string"]</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">import Nanoquery.IO
 
new(File, fname).create().write(string)</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">
writeFile("filename.txt", "An arbitrary string")
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use System.IO.File;
 
class WriteFile {
Line 599 ⟶ 758:
writer→WriteString("this is a test string");
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let write_file filename s =
let oc = open_out filename in
output_string oc s;
Line 612 ⟶ 771:
let filename = "test.txt" in
let s = String.init 26 (fun i -> char_of_int (i + int_of_char 'A')) in
write_file filename s</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 618 ⟶ 777:
 
In Standard Pascal, a list of identifiers in the program header sets up a list of file handlers.
<langsyntaxhighlight Pascallang="pascal">{$ifDef FPC}{$mode ISO}{$endIf}
program overwriteFile(FD);
begin
writeLn(FD, 'Whasup?');
close(FD);
end.</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="bash">./overwriteFile >&- <&- 0>/tmp/foo # open file descriptor with index 0 for writing</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 632 ⟶ 791:
The modern recommended way, is to use one of these CPAN modules:
 
<langsyntaxhighlight lang="perl">use File::Slurper 'write_text';
write_text($filename, $data);</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">use Path::Tiny;
path($filename)->spew_utf8($data);</langsyntaxhighlight>
 
Traditional way, in case using CPAN modules is not an option:
 
<langsyntaxhighlight lang="perl">open my $fh, '>:encoding(UTF-8)', $filename or die "Could not open '$filename': $!";
print $fh $data;
close $fh;</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
Deep in the heart of the compiler itself, after much huffing and puffing, the following code can be found:
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<lang Phix>fn = open(outfile,"wb")
<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>
string img = repeat(' ',SizeOfImage)
<!--</syntaxhighlight>-->
...
lines can also be {"line 1","line 2"} (note that a \n is appended to each line) or other multiline/triplequoted text.<br>
SetCheckSum(img,SizeOfImage)
See also open(), puts(), printf(), (neither of which add any \n), close(), temp_file(), create_directory()...
puts(fn,img)
close(fn)</lang>
Obviously as that can successfully write a binary executable, simple strings are no problem, except that when dealing with text you would normally want automatic line ending conversion enabled, so drop the 'b' (binary) mode option, ie the "wb" above should be just "w".
 
The distribution also includes the file builtins\writefile.e which declares
<lang Phix>global function write_file(object file, sequence data, integer as_text = BINARY_MODE, integer encoding = ANSI, integer with_bom = 1)</lang>
which is intended to be a one-line call with full unicode support, however as yet it is neither properly documented nor adequately tested.
 
=={{header|PHP}}==
<syntaxhighlight lang ="php">file_put_contents($filename, $data)</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(out "file.txt"
(prinl "My string") )</langsyntaxhighlight>
 
=={{header|Pike}}==
<langsyntaxhighlight Pikelang="pike">Stdio.write_file("file.txt", "My string");</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Writes all running process details to a file in the current directory.
<langsyntaxhighlight lang="powershell">
Get-Process | Out-File -FilePath .\ProcessList.txt
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
EnableExplicit
 
Line 693 ⟶ 846:
CloseConsole()
EndIf
</syntaxhighlight>
</lang>
 
{{out|Output (contents of 'output.exe')}}
Line 701 ⟶ 854:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">with open(filename, 'w') as f:
f.write(data)</langsyntaxhighlight>
 
Starting in Python 3.4, we can use <code>pathlib</code> to reduce boilerplate:
 
<langsyntaxhighlight lang="python">from pathlib import Path
 
Path(filename).write_text(any_string)
Path(filename).write_bytes(any_binary_data)</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="racket">#lang racket/base
(with-output-to-file "/tmp/out-file.txt" #:exists 'replace
(lambda () (display "characters")))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>spurt 'path/to/file', $file-data;</langsyntaxhighlight>
or
<syntaxhighlight lang="raku" perl6line>'path/to/file'.IO.spurt: $file-data;</langsyntaxhighlight>
 
=={{header|RATFOR}}==
<syntaxhighlight lang="ratfor">
 
# Program to overwrite an existing file
 
open(11,FILE="file.txt")
101 format(A)
write(11,101) "Hello World"
close(11)
 
end
</syntaxhighlight>
 
 
=={{header|REXX}}==
===version 1===
<syntaxhighlight lang="rexx">
<lang rexx>of='file.txt'
/*REXX*/
 
of='file.txt'
'erase' of
s=copies('1234567890',10000)
Call charout of,s
Call lineout of
Say chars(of) length(s) </langsyntaxhighlight>
{{out}}
<pre>100000 100000</pre>
Line 742 ⟶ 912:
===version 2===
This REXX version doesn't depend on any (operating system) host commands.
<langsyntaxhighlight 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. */
/* [↓] 50 bytes, including the fences.*/
Line 749 ⟶ 919:
call charout oFID, copies($,1000), 1 /*write the longish text to the file. */
/* [↑] the "1" writes text ──► rec #1*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
<br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
write("myfile.txt","Hello, World!")
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
The file is closed at the end of the block.
<langsyntaxhighlight lang="ruby">open(fname, 'w'){|f| f.write(str) }</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">use std::fs::File;
use std::io::Write;
 
Line 770 ⟶ 940:
write!(file, "{}", data)?;
Ok(())
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.io.{File, PrintWriter}
 
object Main extends App {
Line 782 ⟶ 952:
" frictional radial anti-stabilizer vectronize from the flumberboozle to the XKG virtual port?")
close()}
}</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">put "New String" into file "~/Desktop/myFile.txt"</langsyntaxhighlight>
 
=={{header|Sidef}}==
With error handling:
<langsyntaxhighlight lang="ruby">var file = File(__FILE__)
file.open_w(\var fh, \var err) || die "Can't open #{file}: #{err}"
fh.print("Hello world!") || die "Can't write to #{file}: #{$!}"</langsyntaxhighlight>
Without error handling:
<langsyntaxhighlight lang="ruby">File(__FILE__).open_w.print("Hello world!")</langsyntaxhighlight>
=={{header|Smalltalk}}==
{{works with | Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">'file.txt' asFilename contents:'Hello World'</langsyntaxhighlight>
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">#.writetext("file.txt","This is the string")</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun writeFile (path, str) =
(fn strm =>
TextIO.output (strm, str) before TextIO.closeOut strm) (TextIO.openOut path)</langsyntaxhighlight>
 
=={{header|Tcl}}==
 
<langsyntaxhighlight Tcllang="tcl">proc writefile {filename data} {
set fd [open $filename w] ;# truncate if exists, else create
try {
Line 815 ⟶ 985:
close $fd
}
}</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
content="new text that will overwrite content of myfile"
Line 829 ⟶ 999:
IF (status=="CREATE") ERROR/STOP CREATE ("myfile",seq-o,-std-)
ENDLOOP
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 848 ⟶ 1,018:
Print #1, Text
Close #Nb
End Sub</langsyntaxhighlight>
 
=={{header|VBScript}}==
Text file created or overwritten in the same folder as the script.
<syntaxhighlight lang="vb">
<lang vb>
Set objFSO = CreateObject("Scripting.FileSystemObject")
 
Line 865 ⟶ 1,035:
 
Set objFSO = Nothing
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Sub Main()
Line 876 ⟶ 1,046:
 
End Module
</syntaxhighlight>
</lang>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
import os
 
os.write_file('./hello_text.txt', 'Hello there!') or {println('Error: failed to write.') exit(1)}
</syntaxhighlight>
 
=={{header|Wren}}==
The easiest way to overwrite a file in Wren is to 'create' it again which truncates the existing contents.
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
 
// create a text file
Line 896 ⟶ 1,073:
 
// check it worked
System.print(File.read("hello.txt"))</langsyntaxhighlight>
 
{{out}}
Line 905 ⟶ 1,082:
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="scheme">(define n (open-output-file "example.txt"))
(write "(Over)write a file so that it contains a string." n)
(close-output-port n)</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">[FSet(FOpen("output.txt", 1), ^o);
Text(3, "This is a string.");
]</langsyntaxhighlight>
 
=={{header|Xtend}}==
<langsyntaxhighlight lang="java">
package com.rosetta.example
 
Line 928 ⟶ 1,105:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">open "output.txt" for writing as #1
print #1 "This is a string"
close #1</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl"> // write returns bytes written, GC will close the file (eventually)
File("foo","wb").write("this is a test",1,2,3); //-->17
 
f:=File("bar",wb");
data.pump(f,g); // use g to process data as it is written to file
f.close(); // don't wait for GC</langsyntaxhighlight>
9,486

edits