codescracker


c++

C++ Steps to Process a File in Program



« Previous Tutorial Next Tutorial »


Before you actually start using and manipulating files in your C++ programs, let's discuss the steps you need to follow in order to use files in your C++ program.

Here are the steps listed that need to be followed in the order to process a file in a C++ program. The five steps to use files in your C++ program are:

  1. Determine the type of link required.
  2. Declare a stream for the desired type of link.
  3. Attach the desired file to the stream.
  4. Now process as required.
  5. Close the file-link with stream.

Let's discuss these steps in details now. To facilitate your understanding, I'll be using an example for it. For instance, if you have to write a program for the following:

Get rollnumber and marks of the students of a class (get these details from user) and store these details into a file called marks.dat.

Let's now discuss the above mentioned five steps with the help of above example. But before this, shall I tell you an interesting thing - you've been working with file streams right from the day one of C++ programming. This is because, (I/O) devices are implemented as files in C++. This cin and cout are actually the streams that you use for input and output. The cin, the input stream, is linked to keyboard and cout, the output stream is linked to monitor.

Step 1 - Determine the type of link required

First step requires the identification of type of link required. If the data is to be brought in from a file to memory, the the link can be said to be File-to-Memory link. Similarly, if the data (after some processing) is to be sent from memory to file, then the link can be said to be Memory-to-File link. And if a situation demands both types of links, then two-way (File-to-Memory and Memory-to-File) link can be created.

Predefined stream cin is an example of File-to-Memory link. Since devices are treated as files, keyboard is also treated as file. With cin, data comes from the file i.e., keyboard to Memory and hence file-to-memory link and with cout, data goes from memory to file i.e., monitor, hence Memory-to-File link. We can summarize those link as follows :

Link Used for
File-to-Memory
(IN TO the Memory)
Input purposes i.e., to bring data from file to memory for further processing.
Memory-to-File
(OUT FROM the Memory)
Output purposes i.e., to send processed data from memory to the file.
File-to-Memory/Memory-to-File Input/Output purposes.

Example Processing : Step 1

In the example-problem given above, it is given that data is to be read from the user i.e., through the keyboard (file) the data should be brought in memory (for which cin is already declared) and then these read details are to be stored in a file i.e., from memory, data should be sent in the file called marks.dat.

For the reading purpose, file-to-memory link is required for keyboard but for this cin is already declared and to store this data in file, the memory-to-file link is required. Since for marks.dat, no predefined link is available, we'll have to create this type of link.

Thus, we have determined the type of link required for file marks.dat, which is Memory-to-File type link.

Step 2 - Declare a stream for the desired type of link

After determining the type of link required, the next step is to create a stream for it. In order to create file streams, the header file fstream.h is included in the program and if you have included fstream.h then you need not include iostream.h as cin, cout declarations are also available in fstream.h.

For different types of links, different streams classes are used for stream declarations. For File-to-Memory (i.e., input) type of link, ifstream class-type's stream is declared. For example,

ifstream fin;       //stream name here is fin

You can choose any name (meeting the identifier naming rules and conventions) for the stream being declared). For Memory-to-File (i.e., output) type of link, ofstream class-type's stream is declared. And for File-to-Memory/Memory-to-File (i.e., I/O) type of link, fstream class-type's stream is declared. For example,

ofstream fout;       //stream name here is fout.
fstream fio ;       //stream name here is fio.

Following table summarizes these stream types as :

Type of Link Stream Class Example Declaration
File-to-Memory (IN TO the Memory) ifstream ifstream fin ;
Memory-to-File (OUT FROM the Memory) ofstream ofstream fout ;
File-to-Memory/Memory-to-File fstream fstream fio ;

Example Processing : Step 2

For the above mentioned example, we have already determined the link type to be Memory-to-File for file marks.dat. In order to declare a stream for it, we may write as follows :

ofstream fout ;       //stream name here is fout

Step 3 - Attach the desired file to the declared stream

After declaring streams, the next step is to link the file with the declared stream. This is done by opening the desired file.

For example, if a file named sample.dat is to be opened in input mode i.e., linked to a stream of ifstream type, we can do it in the following two ways :

1st Way:
ifstream fin("Sample.dat", ios::in) ;        //using constructor

2nd Way:
fin open("Sample.dat", ios::in) ;        //using open()

Notice that in the above examples, a file mode (ios::in here) is used. ios::in is the default file mode for ifstream type of stream.

Similarly, in order to open a file, say oput.txt, in output mode i.e., to link it with a stream of ofstream type, we may write :

ofstream fout("oput.txt", ios::out) ;     //using constructor

Or as ofstream fout :

fout.open("oput.txt", ios::out) ;      //using open()

To open a file, say newfile.txt, in I/O mode (stream of fstream) type, we may write as

fstream fio("newfile.txt", ios::in | ios::out) ;       //using constructor

Or as fstream fio:

fio.open("newfile.txt", ios::in | ios::out) ;       //using open

Notice that, multiple file modes are separated by a bitwise or (|) pipe sign.

Example Processing : Step 3

Now, with all the information/knowledge gained so fat, let us apply this on our example problem given above.

We may either combine step 2 and step 3 as follows :

ofstream fout("marks.dat", ios::out) ;

Or we may write then separately as :

ofstream fout ;
fout.open("marks.dat", ios::out) ;

Step 4 - Process as required

Under this step, whatever processing is required for the given problem, is performed for instance, our given example-problem requires us to read marks and rollno's of students of a class and store them into file called marks.dat.

Example Processing : Step 4

For this, we already have declared the stream and linked our file marks.dat with it. Now its time for processing. The code fragment for processing is given below :

:
char ans = 'y' ;
int rollno ;
float marks ;

while(ans == 'y' || ans == 'Y')
{
	cout << "\nEnter roll number : " ;
	cin >> rollno ;
	cout << "\nEnter marks : " ;
	cin >> marks ;
	
		/* now student's rollno and marks have been read these details are to be
		 * put into the file's buffer, in order to store them on to the file 
		 */
		
	fout << rollno << '\n' << marks << '\n' ;
	
		/* Notice that the way we send details to output buffer cout, same way we have
		 * sent those details to output buffer fout. Also, notice that we have also
		 * sent new line ('\n') after every piece of data. It is done to separate various
		 * data items. 
		 */
		
	cout << "\nWant to enter more ? (y/n) " ;
	cin >> ans ;
	
}   //end of while

Step 5 - Close the file link with stream

This is the final step where we de-link the file with stream. This is performed through close() function. For example, if the file-stream is fin, then we need to write as :

fin.close();

Similarly, if the stream-name is fio, we'll write it as :

fio.close();

Notice that to de-link a file, there is no need to mention file name, only stream-name (to which the file is linked) is required.

Example Processing : Step 5

To de-link our file marks.dat with the stream fout, we need to write :

fout.close() ;

The Complete Example Program

If we put together all the pieces of codes used for our example-problem, the program will look like the one given below :

Get rollnumbers and marks of the students of a class (get from the user) and store these details into a file called marks.dat :

/* C++ Steps to Process a File in a Program
 * This program demonstrates, how to process
 * a file in a C++ program */

#include<conio.h>
#include<fstream.h>
void main()
{
	clrscr();
	ofstream fout;         // stream decided and declared - step 1 & 2
	fout.open("marks.dat", ios::out);       // file linked - step 3
	char ans = 'y' ;         // process as required - step 4 begins
	int rollno;
	float marks ;
	while(ans == 'y' || ans == 'Y')
	{
		cout << "\nEnter Rollno. : " ;
		cin >> rollno ;
		cout << "\nEnter Marks : " ;
		cin >> marks ;
		fout << rollno << '\n' << marks << '\n' ;
		cout << "\nWant to enter more ? (y/n) " ;
		cin >> ans ;
	}

	fout.close() ;        // de-link the file - step 5
	getch();
}

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

c++ steps to process a file in program

Now, in the same folder where you stored your program's .cpp file, you'll find a file namely marks.dat, the one you created through your above C++ program. You can open this file in Notepad or Wordpad or any other text editor to see its contents. This file will contains all the roll number with marks separated by newline.

To view the file through TurboC++, you may also do as explained in the following lines.

After executing the above program in TurboC++, do one thing. Click upon DOS Shell option under File section present approximately at the left top corner. And then upon the dos prompt, type the following command :

type marks.dat

And you'll see the contents of file you've created just now through your program. And to get back to your program screen in TurboC++, type EXIT at the prompt and hit enter.

More Examples

Here are some more C++ example programs listed, that you can go for. These programs also handles file:


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test