codescracker


c++

C++ Sequential I/O Operations with Files



« Previous Tutorial Next Tutorial »


The file stream classes support a number of member functions for performing the input and output operations on files. The functions get() and put() are capable of handling a single character at a time. The function getline() lets you handle multiple characters at a time. Another pair of functions i.e., read() and write() are capable of reading and writing blocks of binary data.

The get(), getline() and put() Functions

The functions get() and put() are byte-oriented. That is, get() will read a byte of data and put() will write a byte of data. The get() has many forms, but the most commonly used version is shown here, along with put() :

istream & get(char & ch) ;
ostream & put(char ch) ;

The get() function reads a single character from the associated stream and puts that value in ch. It returns a reference to the stream. The put() writes the value of ch to the stream and returns a reference to the stream.

The following program displays the contents of a file on the screen. It uses the get() function :

/* C++ Sequential Input/Output Operations on Files */

#include<iostream.h>
#include<stdlib.h>
#include<fstream.h>
#include<conio.h>
void main()
{
	char fname[20], ch;
	ifstream fin;      // create an input stream
	clrscr();

	cout<<"Enter the name of the file: ";
	cin.get(fname, 20);
	cin.get(ch);

	fin.open(fname, ios::in);       // open file
	if(!fin)           // if fin stores zero i.e., false value
	{
		cout<<"Error occurred in opening the file..!!\n";
		cout<<"Press any key to exit...\n";
		getch();
		exit(1);
	}

	while(fin)                  // fin will be 0 when eof is reached
	{
		fin.get(ch);         // read a character
		cout<<ch;       // display the character
	}

	cout<<"\nPress any key to exit...\n";
	fin.close();
	getch();
}

Here is the sample output of the above C++ program. Let's suppose that the file contain the following information:

c++ sequential input output operations on files

As stated, when the end-of-file is reached, the stream associated with the file becomes zero. Therefore, when fin reaches the end of the file, it will be zero causing the while loop to stop.

The next program uses the put() function to write all characters with ASCII values 33 to 127 to a file called Aschars:

/* C++ Sequential Input/Output Operations with Files */

#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
	ofstream fout;         // create output stream
	char ch;
	int line=0;
	int i;
	clrscr();

	fout.open("Aschars", ios::app) ;
	if(!fout)              // if fout is zero
	{
		cout<<"The file cannot be opened..!!\n";
		cout<<"Press a key to exit...\n";
		getch();
		exit(1);
	}
	/* write the characters */
	for(i=33; i<128; i++)
	{
		fout.put((char)(i));
	}

	fout.close();
	/* now display the contents of the file */

	ifstream fin;
	fin.open("Aschars", ios::in);

	fin.seekg(0);
	for(i=33; i<128; i++)
	{
		fin.get(ch);             // read a character
		cout<<i<<" = ";        // display the character
		cout.put((char)(i));
		cout<<"\t";
		if(!(i%8))
		{
			cout<<"\n";
			line++;
		}
		if(line>22)
		{
			system("PAUSE");
			line = 0;
		}
	}

	cout<<"\n\nPress a key to exit..\n";
	getch();
}

Here is the sample output of the above C++ program:

sequential input output operations

The Other Forms of get() Function

In addition to the form shown earlier, there are several other forms of get() function. Two most commonly used form shave the following prototypes :

istream & get(char ∗ buf, int num, char delim = '\n') ;      // #1
int get() ;                                                  // #2

The first form (#1) reads characters into a character array pointed to bye buf until either num characters have been read, or the character specified by delim has been encountered. For example, the following statements :

char line[40] ;
cin.get(line, 40, '$') ;

will read characters into line until either 40 characters are read or '$' character is encountered, whichever occurs earlier. That is, if the input given in response to above statement is as follows :

Value is $ 177.5

then line will be storing

value is

And if the input given is as follows :

The amount is 17.5

The contents of line will be

The amount is 17.5.

The array pointed to by buf (any user defined name) will be null-terminated by get(). If no delim character is specified, by default a newline character acts as a delimiter. If the delimiter character is encountered in the input stream the get() function does not extract it. Rather, the delimiter character remains in the stream until the next input operation.

The second form (#2) of get() returns the next character form the stream. It returns EOF if the end of the file is encountered. For example, the following code fragment illustrates it :

int i;
char ch;
ch = i = fin.get() ;

If the input given is A, then the value of i will be 65 (ASCII value of A) and the value of ch will be 'A'.

The getline() Function

Another member function that performs input is getline() whose prototype is :

istream & getline(char * buf, int num, char delim = '\n') ;

As you can see, this function in virtually identical to get(buf, num, delim) version of get(). The function getline() also reads characters from input stream and puts them in the array pointed to by buf until either num character have been read, or the character specified by delim is encountered. If not mentioned, the default value of delim is newline character.

The read() and write() Functions

Another way of reading and writing blocks of binary data is to use C++'s read() and write() functions. Their prototypes are :

istream & read( (char *) & buf, int sizeof(buf) ) ;
ostream & write( (char *) & buf, int sizeof(buf) ) ;

The read() function reads sizeof(buf) (it can be any other integer value also) bytes from the associated stream and puts them in the buffer pointed to by buf. The write() function writes sizeof(buf) (it can be any other integer value also) bytes to the associated stream from the buffer pointed to by buf.

As you see, these functions take two arguments. The first is the address of variable buf, and the second is the length of that variable in bytes. The address of the variable must be type cast to type char * (i.e., a pointer to character type).

The data written to a file using write() can only be read accurately using read().

The following program writes a structure to the disk and then reads it back in using write() and read() functions :

/* C++ Sequential Input and Output Operations with Files */

#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>

struct customer
{
	char name[20];
	float balance;
};

void main()
{
	clrscr();
	customer savac;
	cout<<"Enter your name: ";
	cin.get(savac.name, 20);
	cout<<"Enter balance: ";
	cin>>savac.balance;

	ofstream fout;
	fout.open("Saving", ios::out | ios::binary);    // open output file
	if(!fout)
	{
		cout<<"File can\'t be opened..!!\n";
		cout<<"Press any key to exit...\n";
		getch();
		exit(1);
	}

	fout.write((char *) & savac, sizeof(customer));    // write to file
	fout.close();	  // close connection

	// read it back now
	ifstream fin;
	fin.open("Saving", ios::in | ios::binary);    // open input file
	fin.read((char *) & savac, sizeof(customer));     // read structure
	cout<<savac.name;            // display structure now
	cout<<" has the balance amount of Rs. "<<savac.balance<<"\n";
	fin.close();

	cout<<"\nPress a key to exit...\n";
	getch();
}

Here is the sample run of the above C++ program:

sequential input output operations on files

As you can see, only a single call to read() and write() is necessary to read or write the entire structure. Each individual field need not be read or written separately.

If the end of the file is reached before the specified number of characters have been read, the read() simply stops, and the buffer contains as many characters as were available.

Reading and Writing Class Objects

The functions read() and write() can also be used for reading and writing class objects. These functions handle the entire structure of an object as a single unit, using the computer's internal representation of data. For example, the function write() copies a class object from memory byte by byte with no conversion. But one thing that must be remembered is that only data members are written to the disk file and not the member functions.

The length of an object is obtained by sizeof operator and it represents the sum total of lengths of all data members of the object. Here is an example:

/* C++ Sequential Input and Output Operations with Files */

#include<iostream.h>
#include<fstream.h>
#include<conio.h>
#include<stdlib.h>

class student
{
	char name[20];
	char grade;
	float marks;

	public:
		void getdata(void);
		void display(void);

};

void student::getdata(void)
{
	char ch;
	cin.get(ch);
	cout<<"Enter name: ";
	cin.getline(name, 20);
	cout<<"Enter grade: ";
	cin>>grade;
	cout<<"Enter marks: ";
	cin>>marks;
	cout<<"\n";
}

void student::display(void)
{
	cout<<"Name: "<<name<<"\tGrade: "<<grade<<"\tMarks: "<<marks<<"\n";
}

void main()
{
	clrscr();
	char fname[20];
	student cse[3];    // declare array of 3 objects
	fstream fio;       // input and output file

	cout<<"Enter file name: ";
	cin.get(fname, 20);

	fio.open(fname, ios::in || ios::out);
	if(!fio)
	{
		cout<<"Error occurred in opening the file..!!\n";
		cout<<"Press any key to exit...\n";
		getch();
		exit(1);
	}

	cout<<"Enter details for 3 students:\n\n";
	for(int i=0; i<3; i++)
	{
		cse[i].getdata();
		fio.write((char *)&cse[i], sizeof(cse[i]));
	}

	fio.seekg(0);     /* seekg(0) resets the file to start, to access the file
			   * from the beginning */
	cout<<"The content of "<<fname<<" file are shown below:\n";

	for(i=0; i<3; i++)
	{
		fio.read((char *)&cse[i], sizeof(cse[i]));
		cse[i].display();
	}

	fio.close();

	cout<<"\nPress any key to exit...\n";

	getch();
}

Here is the sample run of the above C++ program:

c++ operations on files

More Examples

Here are some more C++ example programs listed, that you can go for:


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test