Steps to Process a File in C++

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 order to process a file in a C++ program. The five steps to using 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 proceed as needed.
  5. Close the file link with stream.

Let's discuss these steps in detail now. I'll explain it with an example to help you understand.For instance, if you have to write a program for the following.

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

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

Step No. 1: Determine the type of link required

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

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

Link Used for
File-to-Memory
(INTO the Memory)
input purposes, i.e., to bring data from files 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 preceding example-problem, it is stated that data is to be read from the user, i.e., through the keyboard (file), and that the data should be brought into memory (for which cin is already declared), and then these read details are to be stored in a file, i.e., data should be sent in the file called marks.dat from memory.

For reading purposes, a file-to-memory link is required for the keyboard, but for this coin, which is already declared, and to store this data in a 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 a memory-to-file type link.

Step No. 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 is included in the program.

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

ifstream fin;        // The stream name here is fin

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

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

The following table summarizes these stream types as follows:

Type of Link Stream Class Example Declaration
File-to-Memory (INTO 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;     // The stream name here is fout

Step No. 3: Attach the desired file to the 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 type ifstream, 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 the 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 type ofstream, we may write:

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

Alternatively, 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), we may write as

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

Alternatively, 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 and knowledge gained so far, let us apply this to our example problem given above.

We may either combine steps 2 and 3 as follows:

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

Or we may write them separately as

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

Step No. 4: Now proceed as needed

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

Example Processing: Step 4

For this, we have already declared the stream and linked our file marks.dat with it. Now it's 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 the roll number: ";
   cin >> rollno;
   cout << "\nEnter the mark: ";
   cin >> marks;

   /* Now the student's roll number and mark have been read,
    * they must be inserted into the file's buffer
    * in order to be saved on the file
    */

   fout << rollno << '\n'
        << marks << '\n';

   /* It's worth noting that the way we send details to the 
    * output buffer ("cout") is identical to how we send those
    * details to the output buffer ("fout"). Also, notice
    * that we have also sent a 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 No. 5: Close the file link with stream

The final step is to unlink the file from the stream. This is performed through the close() function. For example, if the file stream is fin, then we need to write it as:

fin.close();

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

fio.close();

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

Example Processing: Step 5

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

fout.close() ;

The Complete Example Program

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

Get the roll numbers and grades of students in a class (from the user) and save them in a file called marks.dat:

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

int main()
{
   ofstream fout;
   fout.open("marks.dat", ios::out);
   char ans = 'y';
   int rollno;
   float marks;
   while (ans == 'y' || ans == 'Y')
   {
      cout << "Enter the roll number: ";
      cin >> rollno;
      cout << "Enter the mark: ";
      cin >> marks;
      fout << rollno << '\n' << marks << '\n';
      cout << "\nWant to enter more? (y/n): ";
      cin >> ans;
      cout << endl;
   }

   fout.close();
   return 0;
}

The following snapshot shows the initial output produced by the above program:

c++ steps to process a file example

Now type the roll number and hit the ENTER key, then type the mark and hit the ENTER key again to save the data into the file ("marks.dat") associated with the stream "fout." The following snapshot shows the sample run with some user inputs:

C++ steps to process file program

Now if you open the current directory, the directory where the above C++ source code is saved, then you will see a file "marks.dat" will be available there with the following content:

20495044
98
20495047
78

I included the following snapshot for your understanding.

c++ process file example program

More Examples

C++ Quiz


« Previous Tutorial Next Tutorial »



Follow/Like Us on Facebook


Subscribe Us on YouTube