Write entire file: Difference between revisions
(added Tcl) |
|||
Line 69: | Line 69: | ||
{{out}} |
{{out}} |
||
<pre>100000 100000</pre> |
<pre>100000 100000</pre> |
||
=={{header|Tcl}}== |
|||
<lang Tcl>proc writefile {filename data} { |
|||
set fd [open $filename w] ;# truncate if exists, else create |
|||
try { |
|||
puts -nonewline $fd $data |
|||
} finally { |
|||
close $fd |
|||
} |
|||
}</lang> |
|||
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|zkl}}== |
=={{header|zkl}}== |
Revision as of 22:57, 26 October 2015
You are encouraged to solve this task according to the task description, using any language you may know.
(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
<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
procedure Write_Whole_File is
F: File_Type; File_Name : String := "the_file.txt"; Contents: String := "(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.";
begin
begin Open(F, Mode => Out_File, Name => File_Name); -- overwrite existing file exception when Name_Error => -- file does not yet exist
Create (F, Mode => Out_File, Name => File_Name); -- write new file
end; Put (F, Contents); Close (F);
end Write_Whole_File;</lang>
J
<lang J> characters fwrite filename</lang>
or,
<lang J> characters 1!:2<filename</lang>
Perl 6
<lang perl6>spurt( $filename, $data );</lang>
PHP
<lang php>file_put_contents($filename, $data)</lang>
Python
<lang python> with open(filename, 'w') as f:
f.write(data)
</lang>
Racket
This only replaces the file if it exists, otherwise it writes a new file. <lang racket>#lang racket/base (with-output-to-file "tmp/out-file.txt" #:exists 'replace
(lambda () (display "characters")))</lang>
REXX
<lang rexx>of='file.txt' 'erase' of s=copies('1234567890',10000) Call charout of,s Call lineout of Say chars(of) length(s) </lang>
- Output:
100000 100000
Tcl
<lang Tcl>proc writefile {filename data} {
set fd [open $filename w] ;# truncate if exists, else create try { puts -nonewline $fd $data } finally { close $fd }
}</lang>
A more elaborate version of this procedure might take optional arguments to pass to fconfigure (such as encoding) or open (such as permissions).
zkl
<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</lang>