Difference between revisions of "Append a string to a file"

From CodeCodex

(Erlang)
(Implementations)
Line 106: Line 106:
 
   TextIO.closeOut out
 
   TextIO.closeOut out
 
  end
 
  end
 +
</pre>
 +
 +
=== Tcl ===
 +
<pre class="tcl">
 +
set f [open test.txt w]
 +
puts $f "aString"
 +
close $f
 
</pre>
 
</pre>
  
Line 126: Line 133:
 
[[Category:Ruby]]
 
[[Category:Ruby]]
 
[[Category:Standard ML]]
 
[[Category:Standard ML]]
 +
[[Category:Tcl]]
 
[[Category:Zsh]]
 
[[Category:Zsh]]
  
 
[[Category:I/O]]
 
[[Category:I/O]]

Revision as of 18:48, 15 February 2011

Implementations

C

 #include <stdio.h>
 
 int main() {
   FILE *out = fopen("filename", "a");
   fprintf(out, "%s", "aString");
   fclose(out);
   return 0;
 }

C++

 #include <iostream>
 #include <fstream>
 
 int main() {
   std::ofstream out("filename", std::ios::app);
   out << "aString";
   out.close();
   return 0;
 }

Common Lisp

  (with-open-file (stream "filename" :direction :output :if-exists :append)
     (format stream "append this"))

Erlang

append_file(Filename, Bytes) ->
    case file:open(Filename, [append]) of
        {ok, IoDevice} ->
            file:write(IoDevice, Bytes),
            file:close(IoDevice);
        {error, Reason} ->
            io:format("~s open error  reason:~s~n", [Filename, Reason])
    end.

Haskell

appendFile "filename" "aString"

Java

     try {
         BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));
         out.write("aString");
         out.close();
     } catch (IOException e) {
     }

OCaml

 let out = open_out_gen [Open_wronly; Open_append; Open_creat; Open_text] 0o666 "filename" in
   output_string out "aString";
   close_out out

Perl

 open OUT, ">>", "filename" or die "Couldn't open file: $!\n";
 print OUT "aString";
 close OUT;

PHP

 $fp = fopen("filename", "a");
 if($fp) {
     fwrite($fp, "aString");
     fclose($fp);
 }

Python

 try:
     out=open("filename", "a")
     out.write("aString")
     out.close()
 except IOError:
     pass

Ruby

open("filename", "a") do |f|
  f.puts "aString"
end

Standard ML

 let
   val out = TextIO.openAppend "filename"
 in
   TextIO.output (out, "aString");
   TextIO.closeOut out
 end

Tcl

set f [open test.txt w] 
puts $f "aString"
close $f

Zsh

[ -w filename ] && print "aString" >> filename