Write entire file

From Rosetta Code
Task
Write entire file
You are encouraged to solve this task according to the task description, using any language you may know.
Task

(Over)write a file so that it contains a string.


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.

Ada[edit]

with Ada.Text_IO;  use Ada.Text_IO;
 
procedure Write_Whole_File is
File_Name : constant String := "the_file.txt";
 
F : File_Type;
begin
begin
Open (F, Mode => Out_File, Name => File_Name);
exception
when Name_Error => Create (F, Mode => Out_File, Name => File_Name);
end;
 
Put (F, "(Over)write a file so that it contains a string. " &
"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.");
Close (F);
end Write_Whole_File;
 

ALGOL 68[edit]

IF  FILE   output;
STRING output file name = "output.txt";
open( output, output file name, stand out channel ) = 0
THEN
# file opened OK #
put( output, ( "line 1", newline, "line 2", newline ) );
close( output )
ELSE
# unable to open the output file #
print( ( "Cannot open ", output file name, newline ) )
FI

AutoHotkey[edit]

file := FileOpen("test.txt", "w")
file.Write("this is a test string")
file.Close()

AWK[edit]

 
# syntax: GAWK -f WRITE_ENTIRE_FILE.AWK
BEGIN {
dev = "FILENAME.TXT"
print("(Over)write a file so that it contains a string.") >dev
close(dev)
exit(0)
}
 

BaCon[edit]

String:

SAVE s$ TO filename$

Binary:

BSAVE mem TO filename$ SIZE n

BBC BASIC[edit]

file% = OPENOUT filename$
PRINT#file%, text$
CLOSE#file%

Bracmat[edit]

put$("(Over)write a file so that it contains a string.",file,NEW)

C[edit]

#include <stdio.h>
#include <string.h>
 
int main(void) {
FILE *foo =fopen(filename,"w");
fwrite(data, strlen(data), 1, foo);
fclose(foo);
 
return 0;
}
 

C#[edit]

System.IO.File.WriteAllText("filename.txt", "This file contains a string.");

Clojure[edit]

(spit "file.txt" "this is a string")

Common Lisp[edit]

(with-open-file (str "filename.txt"
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(format str "File content...~%"))

Elixir[edit]

File.write("file.txt", string)

F#[edit]

System.IO.File.WriteAllText("filename.txt", "This file contains a string.")

Fortran[edit]

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.

      OPEN (F,FILE="SomeFileName.txt",STATUS="REPLACE")
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.

The OPEN statement started becoming standard with F77, but a READ or WRITE statement for a file could mix FORMAT style I/O with unformatted I/O - or indeed do both at once. This could be achieved via the An format code, which essentially states "unformatted" because it takes the variable's bit pattern "as is". Thus, a typical 32-bit floating-point variable occupies four bytes so it could be read or written with format code A4 and so on for other sizes. With declarations like REAL*8 X, Fortran programmers are usually well aware of storage sizes.

With F90, constraints were tightened - for our own good, supposedly. A file is opened with FORM="FORMATTED" by default, meaning that text is expected to be involved and all READ or WRITE statements must use the FORMAT facilities for that file. In the example, the * specifies free-format, which is not format free. Contrariwise, if the file is opened with FORM="UNFORMATTED" then the FORMAT facility must not be specified, as in the second WRITE of the example.

There is no particular limit on how much can be written in one go since no fixed record length has been specified, and indeed the text rolled forth via a variable may contain whatever character codes are desired, including CR, LF - but you will have to know whether the record separator is CR, CRLF, LFCR or CR, if you expect the file to be read later as a series of separate records. The output from each WRITE will be followed by the record separator (whichever it is) in the character interpretation in force, usually ASCII these days.

If instead FORM="UNFORMATTED" were specified in the OPEN statement you can still write whatever you wish, but now each output will not be followed by a record terminator. It is usual for such files to have a defined record length and reading or writing more than a record can hold is deemed an error. Previously (as with Fortran IV) the output (or input) would continue into however many successive records were needed. This was convenient when writing a large array of integers or floating-point, or indeed any list of such items. This would be useful when a complex data structure had been devised, and a simple statement with a short list would write the lot to a disc file, or read it back later. This would be far less trouble than working through its many details. One could go further and use EQUIVALENCE to overlay the pieces upon a large single array (called say THELOT) so that one need merely use WRITE(F) THELOT and likewise for reading. However keeping the equivalences correct when changes are made is troublesome. Instead, the data structure's collection of items could be placed in a COMMON work area and a STASH subroutine would for its COMMON statement merely declare an array THELOT of a suitable size without any mention of EQUIVALENCE. A somewhat similar arrangement is provided in pl/i via the BASED facility.

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.

FreeBASIC[edit]

' FB 1.05.0 Win64
 
Open "output.txt" For Output As #1
Print #1, "This is a string"
Close #1

Go[edit]

import "io/ioutil"
 
func main() {
ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
}

Groovy[edit]

 new File("myFile.txt").text = """a big string
that can be
splitted over lines
"""

 

Haskell[edit]

main :: IO ( )
main = do
putStrLn "Enter a string!"
str <- getLine
putStrLn "Where do you want to store this string ?"
myFile <- getLine
appendFile myFile str

J[edit]

   characters fwrite filename

or,

  characters 1!:2<filename

Java[edit]

import java.io.*;
 
public class Test {
 
public static void main(String[] args) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) {
bw.write("abc");
}
}
}

Julia[edit]

function writeFile(filename, data)
f = open(filename, "w")
write(f, data)
close(f)
end
 
writeFile("test.txt", "Hi there.")

Kotlin[edit]

// version 1.1.2
 
import java.io.File
 
fun main(args: Array<String>) {
val text = "empty vessels make most noise"
File("output.txt").writeText(text)
}

Lingo[edit]

----------------------------------------
-- Saves string as file
-- @param {string} tFile
-- @param {string} tString
-- @return {bool} success
----------------------------------------
on writeFile (tFile, tString)
fp = xtra("fileIO").new()
fp.openFile(tFile, 2)
err = fp.status()
if not (err) then fp.delete()
else if (err and not (err = -37)) then return false
fp.createFile(tFile)
if fp.status() then return false
fp.openFile(tFile, 2)
if fp.status() then return false
fp.writeString(tString)
fp.closeFile()
return true
end

LiveCode[edit]

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.

 
put "this is a string" into URL "file:~/Desktop/TestFile.txt"
 

Lua[edit]

function writeFile (filename, data)
local f = io.open(filename, 'w')
f:write(data)
f:close()
end
 
writeFile("stringFile.txt", "Mmm... stringy.")

Nim[edit]

 
writeFile("filename.txt", "An arbitrary string")
 

Objeck[edit]

use System.IO.File;
 
class WriteFile {
function : Main(args : String[]) ~ Nil {
writer ← FileWriter→New("test.txt");
leaving {
writer→Close();
};
writer→WriteString("this is a test string");
}
}

Perl[edit]

The modern recommended way, is to use one of these CPAN modules:

use File::Slurper 'write_text';
write_text($filename, $data);
use Path::Tiny;
path($filename)->spew_utf8($data);

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

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

Perl 6[edit]

spurt $filename, $data;

Phix[edit]

Deep in the heart of the compiler itself, after much huffing and puffing, the following code can be found:

fn = open(outfile,"wb")
...
string img = repeat(' ',SizeOfImage)
...
SetCheckSum(img,SizeOfImage)
puts(fn,img)
close(fn)

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

global function write_file(object file, sequence data, integer as_text = BINARY_MODE, integer encoding = ANSI, integer with_bom = 1)

which is intended to be a one-line call with full unicode support, however as yet it is neither properly documented nor adequately tested.

PHP[edit]

file_put_contents($filename, $data)

PicoLisp[edit]

(out "file.txt"
(prinl "My string") )

PureBasic[edit]

 
EnableExplicit
 
Define fOutput$ = "output.txt" ; enter path of file to create or overwrite
Define str$ = "This string is to be written to the file"
 
If OpenConsole()
If CreateFile(0, fOutput$)
WriteString(0, str$)
CloseFile(0)
Else
PrintN("Error creating or opening output file")
EndIf
PrintN("Press any key to close the console")
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf
 
Output (contents of 'output.exe'):
This string is to be written to the file

Python[edit]

 
with open(filename, 'w') as f:
f.write(data)
 

Racket[edit]

This only replaces the file if it exists, otherwise it writes a new file. Use 'truncate to overwrite the new contents into the existing file.

#lang racket/base
(with-output-to-file "/tmp/out-file.txt" #:exists 'replace
(lambda () (display "characters")))

REXX[edit]

version 1[edit]

of='file.txt'
'erase' of
s=copies('1234567890',10000)
Call charout of,s
Call lineout of
Say chars(of) length(s)
Output:
100000 100000
Output:
(first time use) using Regina REXX (among others) on a Windows or DOS system:
Could Not Find c:\file.txt
100000 100000

version 2[edit]

This REXX version doesn't depend on any (operating system) host commands.

/*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.*/
$ = '<<<This is the text that is written to a file. >>>'
/* [↓] COPIES creates a 50k byte str.*/
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. */



Ring[edit]

 
write("myfile.txt","Hello, World!")
 

Ruby[edit]

The file is closed at the end of the block.

open(fname, 'w'){|f| f.write(str) }

Sidef[edit]

With error handling:

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}: #{$!}"

Without error handling:

File(__FILE__).open_w.print("Hello world!")

Tcl[edit]

proc writefile {filename data} {
set fd [open $filename w] ;# truncate if exists, else create
try {
puts -nonewline $fd $data
} finally {
close $fd
}
}

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

TUSCRIPT[edit]

 
$$ MODE TUSCRIPT
content="new text that will overwrite content of myfile"
LOOP
path2file=FULLNAME (TUSTEP,"myfile",-std-)
status=WRITE (path2file,content)
IF (status=="OK") EXIT
IF (status=="CREATE") ERROR/STOP CREATE ("myfile",seq-o,-std-)
ENDLOOP
 

VBScript[edit]

Text file created or overwritten in the same folder as the script.

 
Set objFSO = CreateObject("Scripting.FileSystemObject")
 
SourceFile = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\out.txt"
Content = "(Over)write a file so that it contains a string." & vbCrLf &_
"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."
 
With objFSO.OpenTextFile(SourceFile,2,True,0)
.Write Content
.Close
End With
 
Set objFSO = Nothing
 

XLISP[edit]

(define n (open-output-file "example.txt"))
(write "(Over)write a file so that it contains a string." n)
(close-output-port n)

Xtend[edit]

 
package com.rosetta.example
 
import java.io.File
import java.io.PrintStream
 
class WriteFile {
def static main( String ... args ) {
val fout = new PrintStream(new File(args.get(0)))
fout.println("Some text.")
fout.close
}
}
 

zkl[edit]

      // 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