Write entire file: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
m (→{{header|Wren}}: Changed to Wren S/H) |
|||
(43 intermediate revisions by 30 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}}==
<
procedure Write_Whole_File is
Line 33 ⟶ 139:
Close (F);
end Write_Whole_File;
</syntaxhighlight>
=={{header|ALGOL 68}}==
<
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</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">contents: "Hello World!"
write "output.txt" contents</syntaxhighlight>
=={{header|AutoHotkey}}==
<
file.Write("this is a test string")
file.Close()</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f WRITE_ENTIRE_FILE.AWK
BEGIN {
Line 61 ⟶ 172:
exit(0)
}
</syntaxhighlight>
=={{header|BaCon}}==
String:
<syntaxhighlight lang
Binary:
<
=={{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}}==
<
PRINT#file%, text$
CLOSE#file%</
=={{header|Bracmat}}==
<
=={{header|C}}==
=== Dirty solution ===
<syntaxhighlight lang="c">/*
* Write Entire File -- RossetaCode -- dirty hackish solution
*/
Line 92 ⟶ 240:
freopen("sample.txt","wb",stdout));
}
</syntaxhighlight>
=== Standard function fwrite() ===
<syntaxhighlight lang="c">/*
* Write Entire File -- RossetaCode -- ASCII version with BUFFERED files
*/
Line 191 ⟶ 339:
return EXIT_FAILURE;
}
</syntaxhighlight>
=== POSIX function write() ===
<syntaxhighlight lang="c">/*
* Write Entire File -- RossetaCode -- plain POSIX write() from io.h
*/
Line 259 ⟶ 407:
return 1;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">System.IO.File.WriteAllText("filename.txt", "This file contains a string.");</syntaxhighlight>
=={{header|C++}}==
<
using namespace std;
Line 271 ⟶ 422:
file.close();
return 0;
}</
=={{header|Clojure}}==
<
=={{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}}==
<
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(format str "File content...~%"))</
=={{header|D}}==
<
void main() {
auto file = File("new.txt", "wb");
file.writeln("Hello World!");
}</
=={{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 :
<
public program()
{
File.assign("filename.txt").saveContent("This file contains a string.")
}</
=={{header|Elixir}}==
<
=={{header|F_Sharp|F#}}==
<
=={{header|Factor}}==
<
"this is a string" "file.txt" utf8 set-file-contents</
=={{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.
<
WRITE (F,*) "Whatever you like."
WRITE (F) BIGARRAY</
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}}==
<
Open "output.txt" For Output As #1
Print #1, "This is a string"
Close #1</
=={{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}}==
<
File.Save(User.home &/ "test.txt", "(Over)write a file so that it contains a string.")
End</
=={{header|Go}}==
<
func main() {
ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
}</
=={{header|Groovy}}==
<
that can be
splitted over lines
"""
</syntaxhighlight>
=={{header|Haskell}}==
<
main = do
putStrLn "Enter a string!"
Line 364 ⟶ 630:
putStrLn "Where do you want to store this string ?"
myFile <- getLine
appendFile myFile str</
=={{header|J}}==
<syntaxhighlight lang
or,
<syntaxhighlight lang
=={{header|Java}}==
<
public class Test {
Line 383 ⟶ 649:
}
}
}</
===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}}==
<
f = open(filename, "w")
write(f, data)
Line 392 ⟶ 678:
end
writeFile("test.txt", "Hi there.")</
=={{header|K}}==
{{works with|ngn/k}}
<syntaxhighlight lang=K>"example.txt" 0:"example file contents"</syntaxhighlight>
=={{header|Kotlin}}==
<
import java.io.File
Line 402 ⟶ 692:
val text = "empty vessels make most noise"
File("output.txt").writeText(text)
}</
=={{header|Lingo}}==
<
-- Saves string as file
-- @param {string} tFile
Line 424 ⟶ 714:
fp.closeFile()
return true
end</
=={{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">
put "this is a string" into URL "file:~/Desktop/TestFile.txt"
</syntaxhighlight>
=={{header|Lua}}==
<
local f = io.open(filename, 'w')
f:write(data)
Line 439 ⟶ 729:
end
writeFile("stringFile.txt", "Mmm... stringy.")</
=={{header|Maple}}==
<
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Export["filename.txt","contents string"]</syntaxhighlight>
=={{header|
<syntaxhighlight lang="nanoquery">import Nanoquery.IO
new(File, fname).create().write(string)</syntaxhighlight>
=={{header|Nim}}==
<
writeFile("filename.txt", "An arbitrary string")
</syntaxhighlight>
=={{header|Objeck}}==
<
class WriteFile {
Line 464 ⟶ 758:
writer→WriteString("this is a test string");
}
}</
=={{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:
<
write_text($filename, $data);</
<
path($filename)->spew_utf8($data);</
Traditional way, in case using CPAN modules is not an option:
<
print $fh $data;
close $fh;</
=={{header|Phix}}==
<!--<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: #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>
<!--</syntaxhighlight>-->
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()...
=={{header|PHP}}==
<syntaxhighlight lang
=={{header|PicoLisp}}==
<
(prinl "My string") )</
=={{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">
EnableExplicit
Line 528 ⟶ 846:
CloseConsole()
EndIf
</syntaxhighlight>
{{out|Output (contents of 'output.exe')}}
Line 536 ⟶ 854:
=={{header|Python}}==
<syntaxhighlight lang="python">with open(filename, 'w') as f:
f.write(data)</syntaxhighlight>
Starting in Python 3.4, we can use <code>pathlib</code> to reduce boilerplate:
<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.
<
(with-output-to-file "/tmp/out-file.txt" #:exists 'replace
(lambda () (display "characters")))</
=={{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">
/*REXX*/
of='file.txt'
'erase' of
s=copies('1234567890',10000)
Call charout of,s
Call lineout of
Say chars(of) length(s) </
{{out}}
<pre>100000 100000</pre>
Line 565 ⟶ 912:
===version 2===
This REXX version doesn't depend on any (operating system) host commands.
<
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. */</
<br><br>
=={{header|Ring}}==
<
write("myfile.txt","Hello, World!")
</syntaxhighlight>
=={{header|Ruby}}==
The file is closed at the end of the block.
<
=={{header|Rust}}==
<
use std::io::Write;
Line 593 ⟶ 940:
write!(file, "{}", data)?;
Ok(())
}</
=={{header|Scala}}==
<
object Main extends App {
Line 605 ⟶ 952:
" frictional radial anti-stabilizer vectronize from the flumberboozle to the XKG virtual port?")
close()}
}</
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">put "New String" into file "~/Desktop/myFile.txt"</syntaxhighlight>
=={{header|Sidef}}==
With error handling:
<
file.open_w(\var fh, \var err) || die "Can't open #{file}: #{err}"
fh.print("Hello world!") || die "Can't write to #{file}: #{$!}"</
Without error handling:
<
=={{header|Smalltalk}}==
{{works with | Smalltalk/X}}
<syntaxhighlight lang="smalltalk">'file.txt' asFilename contents:'Hello World'</syntaxhighlight>
=={{header|SPL}}==
<
=={{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}}==
<
set fd [open $filename w] ;# truncate if exists, else create
try {
Line 627 ⟶ 985:
close $fd
}
}</
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}}==
<
$$ MODE TUSCRIPT
content="new text that will overwrite content of myfile"
Line 641 ⟶ 999:
IF (status=="CREATE") ERROR/STOP CREATE ("myfile",seq-o,-std-)
ENDLOOP
</syntaxhighlight>
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 659 ⟶ 1,018:
Print #1, Text
Close #Nb
End Sub</
=={{header|VBScript}}==
Text file created or overwritten in the same folder as the script.
<syntaxhighlight lang="vb">
Set objFSO = CreateObject("Scripting.FileSystemObject")
Line 676 ⟶ 1,035:
Set objFSO = Nothing
</syntaxhighlight>
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Sub Main()
Line 687 ⟶ 1,046:
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}}==
<
(write "(Over)write a file so that it contains a string." n)
(close-output-port n)</
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">[FSet(FOpen("output.txt", 1), ^o);
Text(3, "This is a string.");
]</syntaxhighlight>
=={{header|Xtend}}==
<
package com.rosetta.example
Line 708 ⟶ 1,105:
}
}
</syntaxhighlight>
=={{header|Yabasic}}==
<
print #1 "This is a string"
close #1</
=={{header|zkl}}==
<
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</
|