Writing a text file:

// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
 
int main () {
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else
  {
    cout << "Unable to open file";
  }
  return 0;
}

Reading a text file:

Reading one ''word'' at a time:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
 
int main() {
  ifstream myReadFile;
  myReadFile.open("text.txt");
  string word;
  if (myReadFile.is_open()) {
    while (myReadFile >> word) {
      cout << word << endl;
    }
    myReadFile.close();
  }
  else
  {
    cout << "Unable to open file";
  }
  return 0;
}

OR

Reading one ''line'' at a time:

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
 
int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }
  else
  {
    cout << "Unable to open file";
  }
  return 0;
}
cs-142/fileio.txt · Last modified: 2015/01/07 08:58 by ryancha
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0