Friday, April 22, 2011

Writing to a File

Like any good programming language, C++ and Java have a feature that allows one to write to a file. Though I will only show you the basics, this code should be easy to implement into your code:

C++:

// you will need to check
// your flags if you do not see
// the file in the directory
#include <iostream>
#include <fstream>

using namespace std;

void write(string address, string str) {
  ofstream out(address.c_str());
  out << str;
  out.close();
}

Java:

// import java.io.*;

public void write(String filename, String str) {
  BufferedWriter out = null;
  try {
    out = new BufferedWriter(new FileWriter(filename));
    out.write(str);
    out.close();
  }
  catch (Exception e) {
    System.out.println("Error: "+e.getMessage());
  }
}

No comments:

Post a Comment