Write entire file: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
(Added Lua version)
Line 82: Line 82:
put "this is a string" into URL "file:~/Desktop/TestFile.txt"
put "this is a string" into URL "file:~/Desktop/TestFile.txt"
</lang>
</lang>

=={{header|Lua}}==
<lang Lua>function writeFile (filename, data)
local f = io.open(filename, 'w')
f:write(data)
f:close()
end

writeFile("stringFile.txt", "Mmm... stringy.")</lang>


=={{header|Perl 6}}==
=={{header|Perl 6}}==

Revision as of 16:38, 14 March 2016

Task
Write entire file
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>

ALGOL 68

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

Bracmat

<lang bracmat>put$("(Over)write a file so that it contains a string.",file,NEW)</lang>


C

<lang c>#include <stdio.h>

  1. include <string.h>

int main(void) {

    FILE *foo =fopen(filename,"w");
    fwrite(data, strlen(data), 1, foo);
    fclose(foo);
    return 0;

} </lang>

J

<lang J> characters fwrite filename</lang>

or,

<lang J> characters 1!:2<filename</lang>

Groovy

<lang Groovy> new File("myFile.txt").text = """a big string that can be splitted over lines """ </lang>

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. <lang LiveCode> put "this is a string" into URL "file:~/Desktop/TestFile.txt" </lang>

Lua

<lang Lua>function writeFile (filename, data) local f = io.open(filename, 'w') f:write(data) f:close() end

writeFile("stringFile.txt", "Mmm... stringy.")</lang>

Perl 6

<lang perl6>spurt( $filename, $data );</lang>

Phix

Deep in the heart of the compiler itself, after much huffing and puffing, the following code can be found: <lang Phix>fn = open(outfile,"wb") ... string img = repeat(' ',SizeOfImage) ... SetCheckSum(img,SizeOfImage) 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.

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

version 1

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

This REXX version doesn't depend on any (operating system) host commands. <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.*/

$ = '<<<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. */</lang>



Ring

<lang ring> write("myfile.txt","Hello, World!") </lang>

Ruby

The file is closed at the end of the block. <lang ruby>open(fname, 'w'){|f| f.write(str) }</lang>

Sidef

With error handling: <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}: #{$!}"</lang> Without error handling: <lang ruby>File(__FILE__).open_w.print("Hello world!")</lang>

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).

VBScript

Text file created or overwritten in the same folder as the script. <lang vb> 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 </lang>

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>