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

From CodeCodex

(Erlang)
Line 29: Line 29:
 
   (with-open-file (stream "filename" :direction :output :if-exists :append)
 
   (with-open-file (stream "filename" :direction :output :if-exists :append)
 
     (format stream "append this"))
 
     (format stream "append this"))
 +
</pre>
 +
 +
===Erlang===
 +
<pre>
 +
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.
 
</pre>
 
</pre>
  
Line 105: Line 117:
 
[[Category:C++]]
 
[[Category:C++]]
 
[[Category:Common Lisp]]
 
[[Category:Common Lisp]]
 +
[[Category:Erlang]]
 
[[Category:Haskell]]
 
[[Category:Haskell]]
 
[[Category:Java]]
 
[[Category:Java]]

Revision as of 18:33, 27 December 2010

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

Zsh

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