![]() |
This article contains examples of how to write data to a file in different languages
C[]
#include <stdio.h> int main() { FILE *f; f = fopen("somefile.txt", "w"); if(f != NULL) { fprintf("some text\n"); fclose(f); } return 0; }
Java[]
try { BufferedWriter out = new BufferedWriter(new FileWriter("outfilename")); out.write("aString"); out.close(); } catch (IOException e) { }
Groovy[]
#!/usr/bin/env groovy def writer=new File("FileWrite.out").newWriter() writer.writeLine("contents") writer.close()
Perl[]
#!/usr/local/bin/perl open (MYFILE, '>>data.txt'); print MYFILE "Bob\n"; close (MYFILE);
Python[]
f = open(filename, 'w') f.write(data) f.close()
Or, using with
to ensure that the file is closed properly if an error occurs:
with open(filename, 'w') as f: f.write(data)
Ruby[]
out = File.new(filename, "w+") out << "wrote into file" << "\n" out.close