C++ Files

 

Using fstream library we can work with files. That library function can be included by using <fstream>

 

There are 3 objects included in this library.

 

ofstream: Creates and writes in files

ifstream: Reads from file

fstream: Capable of creating, reading and writing in files.

 

 

Create and write in file

Can be done using ofstream or fstream.

 

Example:

#include <iostream>
#include <fstream>
using namespace std;

int main ()
{
  //create and open a text file
  ofstream MyFile ("filename.txt");

  //Write to the file
  MyFile << "Hello File";
  
  //close the file
  MyFile.close();

  return 0;
}

 

To read a file

To read from a file, use either the ifstream or fstreamobject

 

#include <iostream>
#include <fstream>

using namespace std;

int main ()
{
// Create a text file
  ofstream MyFileWrite ("filename.txt");

// Write to the file
  MyFileWrite << "Hello File!";

// Close the file
  MyFileWrite.close ();

// Create a text string, which is used to output the text file
  string RandomText;

// Read from the text file
  ifstream MyFileRead ("filename.txt");

// Use a while loop together with the getline() function to read the file line by line
  while (getline (MyFileRead, RandomText))
    {
// Output the text from the file
      cout << RandomText;
    }

// Close the file
  MyFileRead.close ();

  return 0;
}