Append a string to a file

From CodeCodex

Implementations[edit]

C[edit]

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

C++[edit]

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

Common Lisp[edit]

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

Erlang[edit]

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[edit]

appendFile "filename" "aString"

Java[edit]

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

OCaml[edit]

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

Perl[edit]

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

PHP[edit]

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

Python[edit]

 with open("filename","a") as out:
     out.write("aString")

Ruby[edit]

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

Standard ML[edit]

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

Tcl[edit]

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

Zsh[edit]

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