Write entire file: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
No edit summary
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(47 intermediate revisions by 33 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">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program writeFile64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessErreur: .asciz "Error open file.\n"
szMessErreur1: .asciz "Error close file.\n"
szMessErreur2: .asciz "Error write file.\n"
szMessWriteOK: .asciz "String write in file OK.\n"
szParamNom: .asciz "./fic1.txt" // file name
sZoneEcrit: .ascii "(Over)write a file so that it contains a string."
.equ LGZONEECRIT, . - sZoneEcrit
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
 
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
// file open
mov x0,AT_FDCWD // current directory
ldr x1,qAdrszParamNom // filename
mov x2,O_CREAT|O_WRONLY // flags
ldr x3,oficmask1 // mode
mov x8,OPEN // Linux call system
svc 0 //
cmp x0,0 // error ?
ble erreur // yes
mov x28,x0 // save File Descriptor
// x0 = FD
ldr x1,qAdrsZoneEcrit // write string address
mov x2,LGZONEECRIT // string size
mov x8,WRITE // Linux call system
svc 0
cmp x0,0 // error ?
ble erreur2 // yes
// close file
mov x0,x28 // File Descriptor
mov x8,CLOSE // Linuc call system
svc 0
cmp x0,0 // error ?
blt erreur1
ldr x0,qAdrszMessWriteOK
bl affichageMess
mov x0,#0 // return code OK
b 100f
erreur:
ldr x1,qAdrszMessErreur
bl affichageMess // display error message
mov x0,#1
b 100f
erreur1:
ldr x1,qAdrszMessErreur1 // x0 <- adresse chaine
bl affichageMess // display error message
mov x0,#1 // return code error
b 100f
erreur2:
ldr x0,qAdrszMessErreur2
bl affichageMess // display error message
mov x0,#1 // return code error
b 100f
100: // program end
mov x8,EXIT
svc #0
qAdrszParamNom: .quad szParamNom
qAdrszMessErreur: .quad szMessErreur
qAdrszMessErreur1: .quad szMessErreur1
qAdrszMessErreur2: .quad szMessErreur2
qAdrszMessWriteOK: .quad szMessWriteOK
qAdrsZoneEcrit: .quad sZoneEcrit
oficmask1: .quad 0644 // this zone is Octal number (0 before)
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
 
</syntaxhighlight>
 
=={{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 33 ⟶ 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 46 ⟶ 152:
# unable to open the output file #
print( ( "Cannot open ", output file name, newline ) )
FI</langsyntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">contents: "Hello World!"
write "output.txt" contents</syntaxhighlight>
 
=={{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 61 ⟶ 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 92 ⟶ 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 191 ⟶ 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 259 ⟶ 407:
return 1;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">System.IO.File.WriteAllText("filename.txt", "This file contains a string.");</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <fstream>
using namespace std;
 
Line 271 ⟶ 422:
file.close();
return 0;
}</langsyntaxhighlight>
=={{header|C#}}==
<lang csharp>System.IO.File.WriteAllText("filename.txt", "This file contains a string.");</lang>
 
=={{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 3.4.x :
<langsyntaxhighlight lang="elena">import system'io.;
public program()
{
[
File new.assign("filename.txt"); .saveContent("This file contains a string.").
}</syntaxhighlight>
]</lang>
 
=={{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 328 ⟶ 544:
 
Option FORM="BINARY" ''does'' allow the reading or writing of however many records are needed to satisfy the I/O list, but, this is not a standard usage.
 
=={{header|Free Pascal}}==
''See also: [[#Pascal]]''
<syntaxhighlight lang="pascal">program overwriteFile(input, output, stdErr);
{$mode objFPC} // for exception treatment
uses
sysUtils; // for applicationName, getTempDir, getTempFileName
// also: importing sysUtils converts all run-time errors to exceptions
resourcestring
hooray = 'Hello world!';
var
FD: text;
begin
// on a Debian GNU/Linux distribution,
// this will write to /tmp/overwriteFile00000.tmp (or alike)
assign(FD, getTempFileName(getTempDir(false), applicationName()));
try
rewrite(FD); // could fail, if user has no permission to write
writeLn(FD, hooray);
finally
close(FD);
end;
end.</syntaxhighlight>
 
=={{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">
w = new Writer["test.txt"]
w.print["I am the captain now."]
w.close[]
</syntaxhighlight>
 
 
=={{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 364 ⟶ 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 383 ⟶ 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 392 ⟶ 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 402 ⟶ 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 424 ⟶ 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 439 ⟶ 729:
end
 
writeFile("stringFile.txt", "Mmm... stringy.")</langsyntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">Export("directory/filename.txt", string);</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Export["filename.txt","contents string"]</syntaxhighlight>
 
=={{header|MathematicaNanoquery}}==
<syntaxhighlight lang="nanoquery">import Nanoquery.IO
<lang Mathematica>Export["filename.txt","contents string"]</lang>
 
new(File, fname).create().write(string)</syntaxhighlight>
 
=={{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 464 ⟶ 758:
writer→WriteString("this is a test string");
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<syntaxhighlight lang="ocaml">let write_file filename s =
let oc = open_out filename in
output_string oc s;
close_out oc;
;;
 
let () =
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</syntaxhighlight>
 
=={{header|Pascal}}==
''See also: [[#Free Pascal|Free Pascal]]''
 
In Standard Pascal, a list of identifiers in the program header sets up a list of file handlers.
<syntaxhighlight lang="pascal">{$ifDef FPC}{$mode ISO}{$endIf}
program overwriteFile(FD);
begin
writeLn(FD, 'Whasup?');
close(FD);
end.</syntaxhighlight>
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:
<syntaxhighlight lang="bash">./overwriteFile >&- <&- 0>/tmp/foo # open file descriptor with index 0 for writing</syntaxhighlight>
 
=={{header|Perl}}==
Line 470 ⟶ 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|Perl 6}}==
 
<lang perl6>spurt 'path/to/file', $file-data;</lang>
or
<lang perl6>'path/to/file'.IO.spurt: $file-data;</lang>
 
=={{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}}==
<syntaxhighlight lang="pike">Stdio.write_file("file.txt", "My string");</syntaxhighlight>
 
=={{header|PowerShell}}==
Writes all running process details to a file in the current directory.
<syntaxhighlight lang="powershell">
Get-Process | Out-File -FilePath .\ProcessList.txt
</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
EnableExplicit
 
Line 528 ⟶ 846:
CloseConsole()
EndIf
</syntaxhighlight>
</lang>
 
{{out|Output (contents of 'output.exe')}}
Line 536 ⟶ 854:
 
=={{header|Python}}==
<syntaxhighlight lang="python">with open(filename, 'w') as f:
<lang python>
f.write(data)</syntaxhighlight>
with open(filename, 'w') as f:
 
f.write(data)
Starting in Python 3.4, we can use <code>pathlib</code> to reduce boilerplate:
</lang>
 
<syntaxhighlight lang="python">from pathlib import Path
 
Path(filename).write_text(any_string)
Path(filename).write_bytes(any_binary_data)</syntaxhighlight>
 
=={{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" line>spurt 'path/to/file', $file-data;</syntaxhighlight>
or
<syntaxhighlight lang="raku" line>'path/to/file'.IO.spurt: $file-data;</syntaxhighlight>
 
=={{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 565 ⟶ 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 572 ⟶ 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}}==
<syntaxhighlight lang="rust">use std::fs::File;
use std::io::Write;
 
fn main() -> std::io::Result<()> {
let data = "Sample text.";
let mut file = File::create("filename.txt")?;
write!(file, "{}", data)?;
Ok(())
}</syntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.io.{File, PrintWriter}
 
object Main extends App {
Line 593 ⟶ 952:
" frictional radial anti-stabilizer vectronize from the flumberboozle to the XKG virtual port?")
close()}
}</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">put "New String" into file "~/Desktop/myFile.txt"</syntaxhighlight>
 
=={{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}}
<syntaxhighlight lang="smalltalk">'file.txt' asFilename contents:'Hello World'</syntaxhighlight>
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">#.writetext("file.txt","This is the string")</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">fun writeFile (path, str) =
(fn strm =>
TextIO.output (strm, str) before TextIO.closeOut strm) (TextIO.openOut path)</syntaxhighlight>
 
=={{header|Tcl}}==
 
<langsyntaxhighlight Tcllang="tcl">proc writefile {filename data} {
set fd [open $filename w] ;# truncate if exists, else create
try {
Line 614 ⟶ 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 628 ⟶ 999:
IF (status=="CREATE") ERROR/STOP CREATE ("myfile",seq-o,-std-)
ENDLOOP
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 646 ⟶ 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 663 ⟶ 1,035:
 
Set objFSO = Nothing
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1
 
Sub Main()
My.Computer.FileSystem.WriteAllText("new.txt", "This is a string", False)
End Sub
 
End Module
</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="wren">import "io" for File
 
// create a text file
File.create("hello.txt") { |file|
file.writeBytes("hello")
}
 
// check it worked
System.print(File.read("hello.txt"))
 
// overwrite it by 'creating' the file again
File.create("hello.txt") {|file|
file.writeBytes("goodbye")
}
 
// check it worked
System.print(File.read("hello.txt"))</syntaxhighlight>
 
{{out}}
<pre>
hello
goodbye
</pre>
 
=={{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}}==
<syntaxhighlight lang="xpl0">[FSet(FOpen("output.txt", 1), ^o);
Text(3, "This is a string.");
]</syntaxhighlight>
 
=={{header|Xtend}}==
<langsyntaxhighlight lang="java">
package com.rosetta.example
 
Line 684 ⟶ 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,476

edits