2
Posted November 27, 2012 by Victor in C/C++ Programming
 
 

File Input and Output in C++

files1
files1

File input and output is simply reading and writing into files. Even though this is a more advanced topic, it is interesting to note how files can be written and read from C++ programs.  All it needs to read or write into a file in C++ are the three basic steps:

  •  Open the file (we will use victor.txt as an example in this guide)
  •  Perform all the reading or writings into your file.
  •  Close your file.

We will show you how to perform the above actions in an interactive manner here below:
 

1.    Opening a file in C++:

We start you off with how to open a file in C++. For you to open a file, you will need to use a C++ function known as the open ( ) function. You can either open a file for reading or for writing. Here is an example how this works:

infile.open(victor.txt, ios::in) // open a file for reading
outfile.open (victor.txt, ios::out) //open a file for writing

2.    Writing and reading From a file

  •   Reading

In C++ the basic class that handles input or reading from files is known as the ifstream. For you to use this class, you will have to include the fstream.ifstream into the header files. The way you are ever going to declare ifstream and use it with a file named victor.txt which contains my age and year of birth is:

include <fstream>
#include <iostream>

using namespace std;

int main()
{
  char name [7];
  int birth;
  int age;
  ifstream inFile;

  inFile.open("victor.txt", ios::in); //Opens victor.txt so that the file can be read
  while (!inFile.eof()) //to ensure that we keep reading until end of file(eof)
  {
    inFile >> name >> age;
  }
}
  •  Writing To a file

On the other hand, the C++ class that handless C++ output is the ofstream class. For you to use the ofstream class, you will have to include fstream.ofstream in your header files. Here is the way in which you are going to declare the ofstream class:

#include <fstream>
#include <iostream>

using namespace std;

int main()
{
  char name[7];
  int age;
  ofstream outFile;

  outFile.open(victor.txt, ios::out)); //Opens victor.txt and creates an outputs the contents in victor.txt through outfile
  outFile<<name<< " " << age;
  outFile.close(); //close the file victor.txt that we had opened for output.
}

3.    Closing a file

Once you have either read the contents of the file or written new content, you can now close your file. The function for closing a file is easy and straightforward as used above. However, once more, here is how to do it:

inFile.close() for closing a file after reading from it.
outFile.close() for closing a file after writing in it.

Victor