FANDOM


16px-Pencil

This article contains examples of how to write data to a file in different languages

C Edit

#include <stdio.h>

int main() {
    FILE *f;
    f = fopen("somefile.txt", "w");
    if(f != NULL) {
        fprintf("some text\n");
        fclose(f);
    }
    return 0;
}

Java Edit

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

Groovy Edit

#!/usr/bin/env groovy

def writer=new File("FileWrite.out").newWriter()
writer.writeLine("contents")
writer.close()

Perl Edit

#!/usr/local/bin/perl
open (MYFILE, '>>data.txt');
print MYFILE "Bob\n";
close (MYFILE);

Python Edit

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 Edit

out = File.new(filename, "w+")
out << "wrote into file" << "\n"
out.close

See Also Edit

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.