File IO in C++ (text and binary files) part II

In the first C++ programming tutorial on file IO we looked at the theory behind file IO.

In this second C++ programming tutorial on file IO we will look at some examples.

Read and Write characters (text file)

In the example below we will write and read characters from a text file.

We will write a character (given by the user) to a file test.txt as long as the answer to the question “Continue?:” is replayed with y (from yes). If we answer with something else the program must close the test.txt file. The last part of the program will read all characters in the file test.txt.


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

int main(int argc, char *argv[])
{
	//code to write characters in a file
	char c, ans;
	ans='y';

	//Open an output stream
	ofstream out ("test.txt");
	if(out.is_open())
	{
		//Loop will continue until something other then y is entered
		while (ans=='y')
		{
			cout <<endl << "Continue ?";
			cin >> ans;
			if(ans=='y')
			{
				cout << endl << "Enter Character :";
				cin >> c;
				out.put(c);
			}
		}
	}
	out.close();

	//code for reading file completely
	ifstream in("test.txt");
	if(in.is_open())
	{
		while(!in.eof())
		{
			c = in.get();
			if(!in.eof())
			cout << c;
		}
	}
	in.close();
}

Special flags

The table below shows the special flags that can be used to manage files. (These flags are used during opening of the files).

ios::app

Opens the file in append mode

ios::ate

Opens the file and set the cursor at end of the
file

ios::binary

Opens the file in binary mode

ios::in

Opens the file for reading

ios::out

Opens the file for writing

ios::trunc

Opens the file and truncates all the contents from
it

Binary copy

In the next example we will copy a binary file to another binary file. We will open two files in binary mode,
one for reading and one for writing.

If both are open then we will copy the content of one file to another.


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

int main(int argc, char *argv[])
{
	//Open an input and output stream in binary mode
	ifstream in("myimage.jpg",ios::binary);
	ofstream out("myimage1.jpg",ios::binary);

	if(in.is_open() && out.is_open())
	{
		while(!in.eof())
		{
			out.put(in.get());
		}
	}

	//Close both files
	in.close();
	out.close();
}

Note: of cource you need to supply the myimage.jpg file to copy (or any other jpg file).

Reading and writing an object

In this last example we will write and read an object (student object) to and from a file:


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

class Student
{
	char name[20];
	int mark;
public:
	void GetStudentData();
	void ShowStudentData();
};

void Student ::  GetStudentData()
{
	cout << "Enter Student Name:" << endl;
	cin >> name;
	cout << "Enter Student Mark:" << endl;
	cin >> mark;
}

void Student ::  ShowStudentData()
{
	cout << "Student Details are:" << endl;
	cout << "Name: " <<  name << endl
		<< "Mark: " <<  mark << endl;
}

int main(int argc, char *argv[])
{
	char ans='y';
	Student sobj;

	//We open student.dat in append mode
	ofstream out("student.dat", ios::app);

	if(out.is_open())
	{
		//Loop will continue until something other then y is entered
		while( ans == 'y')
		{
			cout << endl << "Continue ?";
			cin >> ans;
			if(ans == 'y')
			{
				sobj.GetStudentData();
				out.write((char*) & sobj, sizeof(sobj));
			}
		}
	}
	out.close();

	ifstream in("student.dat");
	if(in.is_open())
	{
		while(!in.eof())
		{
			in.read((char*) &sobj, sizeof(sobj));
			if(!in.eof())
			{
			sobj.ShowStudentData();
			}
		}
	}
	in.close();
}

As you can see there are many ways to do file IO in the C++ programming language.

That is all for this tutorial.

This entry was posted in C++ Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 6 responses to “File IO in C++ (text and binary files) part II”

Why not let us know what you think by adding your own comment!

  1. sarita on October 2nd, 2009:

    contents are very nice
    & unstandable

  2. sharad on July 7th, 2011:

    its simple n understable…gud one

  3. mtanh1988 on January 1st, 2012:

    Very nice samples. Thanks in advance.

  4. Keeran on June 3rd, 2012:

    Thank U !!

  5. urvi on March 22nd, 2013:

    It’s really good…. :)

  6. moh on October 10th, 2013:

    i have file contain of 10 personals
    no name age tel
    1 ghj 33 908777

    10
    requirement read this data from file and insert and sort using BST in c++