INFORMATION FROM DR. EBRAHIMI'S C++ PROGRAMING EASY WAYS

Home                  ABOUT US                    CONTACT US                  TUTORIAL

CHAPTER 9

 

FILE HANDLING:  A DATABASE

 

 

A key feature of the computer is the ability to store information, and to retrieve it at a later time. The information (data) has to be saved somewhere, which is called a file, and has to be under a name, which is called a filename. A program constantly interacts with the files to store, retrieve, modify or delete the data. Traditionally, a file that is used to store or retrieve data is called a data file or an input file. A data file may contain personal information such as the names of employees, their telephone numbers and salaries.

 

You may work interactively with a program and enter the data each time. However, when the input data becomes large, it is necessary to work with a data file rather than typing the data over and over each time. One example of a data file would be supermarket pricing, where a huge amount of data is manipulated.  In today’s web engine, hundreds of files may have to be processed in order to complete a search. The advancement of the Internet has proportionally increased the number of files and their size.  For any organization, data processing and data manipulation are essential operations.  A database runs the day-to-day operations by adding new records, searching for particular record(s), modifying the existing records and generating reports. Due to the real-time demand of data, the efficiency of databases is subject to review and, as a result, a tremendous effort has been spent to secure their reliability.  

 

 

WORKING WITH A DATA FILE

 

In order to work with a data file, whether it is to be used to store data or retrieve data, the following steps need to be taken into consideration.

 

1)                  Include the file stream in the header file section.

2)                  Associate a name with the data file and specify its mode as to whether to output, append or input. This step will open the data file and get it ready.       

3)                  Use the associated file name throughout the program the same way cin and cout are used, except that with cin and cout data are handled by the console (keyboard and screen). 

4)                  Close the file when you are finished.

 

 

 

 

 

 

 

 

 

 

TO ACCESS A DATA FILE FOR INPUT

 

To access a data file to input from, the following steps should be considered:

Text Box: #include <fstream>
using namespace std;

1)         Include the file stream header file. 

                                                               

Text Box: ifstream fin(“datafile.txt”);

2)         Associate an input file name with an input file stream for accessing the data file. 

 

You may indicate explicitly the mode of file access as input:

Text Box: ifstream fin(“datafile.txt”,ios::in);
 

  

 


 

As a convention, the name fin is used which stands for “file in” as the C++ word cin stands for “console in”.

3)         Use the associated file name to access the data the same way cin accesses the data, e.g. from the keyboard.

Text Box: fin>>itemid>>itemprice;
 

             

 

Text Box: fin.close( );
 

4)         Close the file indicating that the data access is terminated.  

 

 

 

EXAMPLE: ACCESSING THE INPUT DATA FILE

The following program demonstrates how an input data file that is already created can be accessed. The input data file may have been previously created either by an editor (such as notepad) or by a program (see the following).

 

 

 

 

 

 

 

 

 

#include <fstream>

#include<iostream>

using namespace std;

main(){

            long int empid;

            int hoursworked;

            double hourlyrate, grosspay;

            ifstream fin ("employee.txt");  

            fin>>empid>>hoursworked>>hourlyrate;

            grosspay= hoursworked * hourlyrate;

cout <<"EMPLOYEE'S ID IS  "<<empid<<endl;

            cout <<"THE GROSS PAY IS "<<grosspay<<endl;

            return 0;      }//MAIN

Text Box: Figure 9.1a – Program to access the input data file and to compute gross pay.
 
Text Box: Figure 9.1c –Output of the program in Figure 9.1a with input data file in Figure 9.1b.
Text Box: EMPLOYEE'S ID IS  1000001
THE GROSS PAY IS 1200
Text Box: 1000001          48        25
Text Box: Figure 9.1b –Input data file employee.txt for Figure 9.1a.

  

 

 

 

 

 


 

The above program only accesses one set of data since there is no loop performed.  However, by looping, the entire data file can be accessed.

 

 

TO WRITE INTO A FILE: OUTPUT FILE

 

To write into a file, or simply to create an output file, the following steps need to be considered:

1) Include the file stream header file. 

Text Box: #include<fstream>
using namespace std;
 

  

 


 

2) Associate an output file name with the file stream. A data file with the given name will be created.

Text Box: ofstream fout(“datafile.out”);
 

  

 

 

 


 

Text Box: ofstream fout(“datafile.out”, ios::out);
 

You may indicate explicitly the mode of file access as output: 

 

As a convention, the name fout is used which stands for “file out” as the C++ word cout stands for “console out”.

3) Use the associated file name to output the data, the same way cout outputs the data to the screen, except that the data will be redirected to the file.

Text Box: fout<<itemid<< “   ”<<itemprice;
 

  


 

           

4) Close the file indicating that the data access is terminated.

Text Box: fout.close( );
 

  

 


 

#include <fstream>

#include<iostream>

using namespace std;

main(){           

int empid,hoursworked;

            float hourlyrate, grosspay;

            ofstream fout  ("salary.txt");   //associating fout with salary.txt

            for (int i=1; i<=5; i++){                      //loop for 5 employees

                        cout<<" ENTER THE EMPLOYEE'S ID "; //interactive data entries

                        cin>>empid;

                        cout<<" ENTER HOURS WORKED ";

                        cin>>hoursworked;

                        cout<<" ENTER THE HOURLY RATE ";

                        cin>>hourlyrate;

                        grosspay= hoursworked * hourlyrate; //compute grosspay

                        fout<<empid<<"  "<<hoursworked <<"  "<<hourlyrate<<"  "

                                    <<grosspay<<endl;                            //writing to a file

                        }//FOR

            fout.close( );

            return 0;     }//MAIN

Text Box: Figure 9.2a – Writing to a file

  

 


 

 

Text Box: Figure 9.2c –Output file named salary.txt
Text Box:  ENTER THE EMPLOYEE'S ID 10001
 ENTER HOURS WORKED 45
 ENTER THE HOURLY RATE 20
 ENTER THE EMPLOYEE'S ID 10002
 ENTER HOURS WORKED 44
 ENTER THE HOURLY RATE 25
 ENTER THE EMPLOYEE'S ID 10003
 ENTER HOURS WORKED 48
 ENTER THE HOURLY RATE 30
 ENTER THE EMPLOYEE'S ID 10004
 ENTER HOURS WORKED 48
 ENTER THE HOURLY RATE 50
 ENTER THE EMPLOYEE'S ID 10005
 ENTER HOURS WORKED 40
 ENTER THE HOURLY RATE 50
 
 
Text Box: 10001  45  20  900
10002  44  25  1100
10003  48  30  1440
10004  48  50  2400
10005  40  50  2000

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 9.2b –Sample output for Figure 9.2a.

 

 

 

 

 

 


 

INPUT FROM KEYBOARD AS WELL AS INPUT FROM DATA FILE: SEARCH

 

Most of today’s programs interact with the user and then access the data file to search and to perform the necessary operations. The standard input routine such as cin will access the keyboard (Standard Input File) in order to receive the input (Search Request) from the user. An external input file will be opened and then, repeatedly, data will be retrieved until a match has occurred or input data have been exhausted to the end (END OF FILE REACHED).

 

#include <fstream>

#include<iostream>

using namespace std;

main(){

            long int accountnumber, searchaccountnumber;

            double balance;

            ifstream fin ("account.txt");

            cout<<"ENTER YOUR ACCOUNT NUMBER  ";

            cin>>searchaccountnumber;

            while(fin>>accountnumber>>balance){

                  if(searchaccountnumber==accountnumber){

                 cout<<accountnumber<<" CURRENT BALANCE IS $"<<balance<<endl;

                 return 1; }

            }//WHILE

cout<<" NO MATCH FOR ACCOUNT "<<searchaccountnumber<<endl;

return 0;    }//MAIN

Text Box: Figure 9.3a – Search for a datum in a data file
 

  

 

 

Text Box: Figure 9.3c –Sample output for Figures 9.3a and 9.3b
Text Box: ENTER YOUR ACCOUNT NUMBER  21003
21003 CURRENT BALANCE IS $365.2
Text Box: 21001  6988.54
21002  13576.90
21003  365.20
21004  3524.78
21005  641.33
21006  75.22
21007  38655.66
21008  47369.71

  

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 9.3b –File named account.txt

  

 

 

 

 


 

The above program asks the user to enter the account number and then the program will repeatedly access the account file and try to match the account number.  Upon succession, it will cout the balance, and exits the program. Otherwise, the program will eventually reach the end of the file, and at that moment the message  “ NO MATCH FOR ACCOUNT” will be displayed.

 

 

MODE OF OPENING A FILE

 

A file can be opened according to the following ways (modes):

A file can be opened as an input file so that data can be retrieved.

 

Text Box: ifstream fin (“data.in”,ios::in);
            
 

  

 

 


 

 The default file mode for ifstream is ios::in

Text Box: ifstream fin (“data.in”); //input stream
            
 

  

 

 

 


 

A file can be opened so that data can be written or output to it.

Text Box: ofstream fout (“data.out”,ios::out);
            
 

  

 

 

 


 

  The default file mode for ofstream is ios::out

Text Box: ofstream fout (“data.out”); 
            
 

  

 

 

 


 

 

 

In addition a file can be for output by adding (appending) data to the end of the existing file.

Text Box: ofstream fout (“data.out”,ios::app);
            
 

  

 

 

A file can be for both input and output ios::in | ios::out

 

Text Box: fstream fout (“data.dat”, ios::in|ios::out);
            
 

  

 

 

 


 

WHAT IS A DATABASE (dbase)

Manipulating data (information) plays an important role in any organization today. In order to manipulate the data, information has to be stored, retrieved, modified or deleted. At any moment new data can be added to a file, or existing information can be retrieved, modified or even deleted. Instead of one file there might be several files needed to store information as well as to interact with other files (file processing). The notion of data manipulation where data may be stored, retrieved, modified or even deleted is called a database.  In addition, there are times when it is necessary to generate reports based on a certain request or computations from the database.

 

 

A JOURNEY FROM BIT TO DATABASE

 

Computer information is represented in binary form using a bit.  Each bit contains a value which is either zero or one. Eight bits represent a byte. Depending on the system one or two bytes represent a character. Several characters form a field or a string. One or more fields make up a record. Multiple records build a stream or a file. Finally several files create a database. However this naming convention may vary slightly, a string may represent the whole file or a database may contain only a single file.

 

 

BUILDING A SIMPLE DATABASE: Create, Display and Search

 

The following program illustrates how easily you can build a simple database by putting a few functions together. For the sake of simplicity, the database program will add, display and search the data immediately, with data modification and deletion performed later. In writing this program, the concern is simplicity rather than efficiency (speed of program or saving space). The three functions for this database are myappend() to add a record to the end of data file, mydisplay() to display entire records, and mysearch() to search  for a particular record.

 

Hosted by www.Geocities.ws

1