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">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program writeFile64.s */
Line 106 ⟶ 109:
.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 128 ⟶ 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 141 ⟶ 152:
# unable to open the output file #
print( ( "Cannot open ", output file name, newline ) )
FI</
=={{header|Arturo}}==
<
write "output.txt" contents</
=={{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 161 ⟶ 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 192 ⟶ 240:
freopen("sample.txt","wb",stdout));
}
</syntaxhighlight>
=== Standard function fwrite() ===
<syntaxhighlight lang="c">/*
* Write Entire File -- RossetaCode -- ASCII version with BUFFERED files
*/
Line 291 ⟶ 339:
return EXIT_FAILURE;
}
</syntaxhighlight>
=== POSIX function write() ===
<syntaxhighlight lang="c">/*
* Write Entire File -- RossetaCode -- plain POSIX write() from io.h
*/
Line 359 ⟶ 407:
return 1;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
<
=={{header|C++}}==
<
using namespace std;
Line 374 ⟶ 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 432 ⟶ 547:
=={{header|Free Pascal}}==
''See also: [[#Pascal]]''
<
{$mode objFPC} // for exception treatment
uses
Line 451 ⟶ 566:
close(FD);
end;
end.</
=={{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 495 ⟶ 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 514 ⟶ 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 523 ⟶ 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 533 ⟶ 692:
val text = "empty vessels make most noise"
File("output.txt").writeText(text)
}</
=={{header|Lingo}}==
<
-- Saves string as file
-- @param {string} tFile
Line 555 ⟶ 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 570 ⟶ 729:
end
writeFile("stringFile.txt", "Mmm... stringy.")</
=={{header|Maple}}==
<
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
=={{header|Nanoquery}}==
<
new(File, fname).create().write(string)</
=={{header|Nim}}==
<
writeFile("filename.txt", "An arbitrary string")
</syntaxhighlight>
=={{header|Objeck}}==
<
class WriteFile {
Line 599 ⟶ 758:
writer→WriteString("this is a test string");
}
}</
=={{header|OCaml}}==
<
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</
=={{header|Pascal}}==
Line 618 ⟶ 777:
In Standard Pascal, a list of identifiers in the program header sets up a list of file handlers.
<
program overwriteFile(FD);
begin
writeLn(FD, 'Whasup?');
close(FD);
end.</
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:
<
=={{header|Perl}}==
Line 632 ⟶ 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}}==
<
=={{header|PowerShell}}==
Writes all running process details to a file in the current directory.
<
Get-Process | Out-File -FilePath .\ProcessList.txt
</syntaxhighlight>
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
EnableExplicit
Line 693 ⟶ 846:
CloseConsole()
EndIf
</syntaxhighlight>
{{out|Output (contents of 'output.exe')}}
Line 701 ⟶ 854:
=={{header|Python}}==
<
f.write(data)</
Starting in Python 3.4, we can use <code>pathlib</code> to reduce boilerplate:
<
Path(filename).write_text(any_string)
Path(filename).write_bytes(any_binary_data)</
=={{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"
or
<syntaxhighlight lang="raku"
=={{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 742 ⟶ 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 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. */</
<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 770 ⟶ 940:
write!(file, "{}", data)?;
Ok(())
}</
=={{header|Scala}}==
<
object Main extends App {
Line 782 ⟶ 952:
" frictional radial anti-stabilizer vectronize from the flumberboozle to the XKG virtual port?")
close()}
}</
=={{header|SenseTalk}}==
<
=={{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}}
<
=={{header|SPL}}==
<
=={{header|Standard ML}}==
<
(fn strm =>
TextIO.output (strm, str) before TextIO.closeOut strm) (TextIO.openOut path)</
=={{header|Tcl}}==
<
set fd [open $filename w] ;# truncate if exists, else create
try {
Line 815 ⟶ 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 829 ⟶ 999:
IF (status=="CREATE") ERROR/STOP CREATE ("myfile",seq-o,-std-)
ENDLOOP
</syntaxhighlight>
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 848 ⟶ 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 865 ⟶ 1,035:
Set objFSO = Nothing
</syntaxhighlight>
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Sub Main()
Line 876 ⟶ 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.
<
// create a text file
Line 896 ⟶ 1,073:
// check it worked
System.print(File.read("hello.txt"))</
{{out}}
Line 905 ⟶ 1,082:
=={{header|XLISP}}==
<
(write "(Over)write a file so that it contains a string." n)
(close-output-port n)</
=={{header|XPL0}}==
<
Text(3, "This is a string.");
]</
=={{header|Xtend}}==
<
package com.rosetta.example
Line 928 ⟶ 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</
|