Page 1 of 1

C++ BEGINNER FILE PROCESSING TUTORIAL C++ BEGINNER FILE PROCESSING TUTORIAL Rate Topic: -----

#1 Elcric  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 101
  • View blog
  • Posts: 453
  • Joined: 02-May 09

Posted 01 August 2009 - 06:29 AM

C++ BEGINNER FILE PROCESSING TUTORIAL


CONTENTS:

• I. ASSUMPTIONS
• II. INTRODUCTION
• III. VOCABULARY
• IV. CREATING A SEQUENTIAL FILE
• V. READING DATA FROM A SEQUENTIAL FILE
• VI. PROBLEMS INVLOVED IN UPDATING A SEQUENTIAL FILE
• VII. CREATING A RANDOM ACCESS FILE
• VIII. WRITING DATA TO A RANDOM ACCESS FILE
• IX. READING DATA FROM A RANDOM ACCESS FILE SEQUENTIALLY

WHAT YOU WILL LEARN IN THIS TUTORIAL:

1. You will learn file processing vocabulary.

2. You will learn how to create a sequential file.

3. You will learn how to read data from a sequential file.

4. You will learn about problems involved in updating a sequential file.

5. You will learn how to create a random access file.

6. You will learn how to write data to a random access file.

7. You will learn how to read data from a random access file.

• I. ASSUMPTIONS

I assume you have a C++ compiler and you want to learn about C++ file processing.

• II. INTRODUCTION

Hello; nice to meet you! Welcome to the “C++ Beginner File Processing Tutorial.”

Please copy and paste the two attached example programs into a file your compiler can read. Then build, compile, and debug the two example programs. Following along, back and forth, between the tutorial and your copy of the two example programs will help you understand the example programs functionality.

//**************************************
//C++ Beginner File Processing Tutorial
//Sequential File
//**************************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fixed;
using std::exit;
using std::ifstream;
using std::ios;
using std::left;
using std::right;
using std::ofstream;
using std::setw;
using std::showpoint;
using std::setprecision;
using std::string;

#endif  //CALC_ERROR_H

class CAccountsPayable
{
	public:

			   CAccountsPayable();
		void   m_CreateSequentialFile();
		void   m_ReadSequentialFile();
			   ~CAccountsPayable();
	private:

		int	account;
		char   lastName[ 15 ];
		char   firstName[ 10 ];
		double balance;

		
};

CAccountsPayable::CAccountsPayable()  //Constructor.
{

}

//************************************
//Creates a sequential file.
//************************************	
void CAccountsPayable::m_CreateSequentialFile()
{
	ofstream outCustomerFile("CustomerFile.dat", ios::out);  //File created for output.
	//Two arguments passed to constructor: filename, and file open mode.
	//ios::out output mode to truncate an existing file and output new data to the file. 
	//ios::out creates a new file if the file does not already exist.
	//By default ofstream oubjects are opened for output; therefore, ios::out was not needed. 
	//ios::app append mode to append data to the end of an existing file.

	int	account		 = 0;
	char   lastName[ 15 ]  = {" "};
	char   firstName[ 10 ] = {" "};
	double balance		 = 0.0;
	int	choice		  = 0;
	bool   exitt		   = false;
	
	if (outCustomerFile.is_open())						//Checks to see if file is open.
	{
	 	system( "CLS" );
		cout << endl << endl << endl;
		cout << "  C++ Beginner File Processing Tutorial" << endl << endl;
		cout << "			 Sequential File" << endl << endl;

		do
		{
			cout << endl << endl << endl;
			cout << "  Please enter customer account number." << endl << endl;
			cout << "  Any number from 1 to 100, for example, 1 " << endl << endl;
			cout << "  and then press Enter => ";
			cin  >> account;
			cout << endl << endl << endl;
			cout << "  You entered " << account;
			cout << endl << endl << endl;
			cout << "  ";
			system ("PAUSE");

			system( "CLS" );
			cout << endl << endl << endl;
			cout << "  Please enter customer last name." << endl << endl;
			cout << "  Maximum 15 characters, for example Jones" << endl << endl;
			cout << "  and then press Enter => ";
			cin  >> lastName;
			cout << endl << endl << endl;
			cout << "  You entered " << lastName;
			cout << endl << endl << endl;
			cout << "  ";
			system ("PAUSE");

			system( "CLS" );
			cout << endl << endl << endl;
			cout << "  Please enter customer first name." << endl << endl;
			cout << "  Maximum 10 characters, for example Roy" << endl << endl;
			cout << "  and then press Enter => ";
			cin  >> firstName;
			cout << endl << endl << endl;
			cout << "  You entered " << firstName;
			cout << endl << endl << endl;
			cout << "  ";
			system ("PAUSE");

			system( "CLS" );
			cout << endl << endl << endl;
			cout << "  Please enter customer account balance." << endl << endl;
			cout << "  for example, 1000 " << endl << endl;
			cout << "  and then press Enter => ";
			cin  >> balance;
			cout << endl << endl << endl;
			cout << "  You entered " << balance;
			cout << endl << endl << endl;
			cout << "  ";
			system ("PAUSE");

			outCustomerFile << account << " " << lastName << " " << firstName << " " << balance << endl;  //One record of four fields each separated by a blank space.

			system( "CLS" );
			cout << endl << endl << endl;
			
			cout << "  Type the number 1 and press return ";
			cout << "to enter another record.  " << endl << endl;
			cout << "  Type 0 and press return to exit. ==> ";
			cin >> choice;
			if ( choice == 0 )
			{
				break;
			}
			if ( choice == 1 )
				exitt = false;
			else
			{
				exitt = true;
			}
		}while( exitt == false );

			outCustomerFile.close();						  //Closes file.
	}
	else
	{
		if(!outCustomerFile)
		{
			system( "CLS" );
			cout << endl << endl << endl;
			cerr << "  Unable to open file.";
			cout << endl << endl << endl;
			cout << "  ";
			system ("PAUSE");
			exit(1);  //Argument 0 is a normal exit, any other value is an error exit.
		}
	}
}

//************************************
//Reads a sequential file.
//************************************	
void CAccountsPayable::m_ReadSequentialFile()
{
	ifstream inCustomerFile("CustomerFile.dat", ios::in);  //File created for input.
	//Two arguments passed to constructor: filename, and file input mode.
	//ios::in input mode to open an existing file for input from the file into the program. 
	//ios::in results in an error message if the file does not already exist.
	
	int	account	   = 0;
	char   lastName[15]  = {" "};
	char   firstName[10] = {" "};
	double balance	   = 0.0;
	
	if (inCustomerFile.is_open())						//Checks to see if file is open.
	{
		while( inCustomerFile >> account >> lastName >> firstName >> balance )
		{
			system ("CLS");
			cout << endl << endl << endl;
			cout << "  Account Number:  " << account   << endl << endl;
			cout << "  Last Name:	   " << lastName  << endl << endl;
			cout << "  First Name:	  " << firstName << endl << endl;
			cout << "  Account Balance: " << balance   << endl << endl;  //One record.
			
			cout << endl << endl << endl;
			cout << "  ";
			system ("PAUSE");
		}

		inCustomerFile.close();						  //Closes file.
	}
	else
	{
		if(!inCustomerFile)
		{
			system( "CLS" );
			cout << endl << endl << endl;
			cerr << "  Unable to open file.";
			cout << endl << endl << endl;
			cout << "  ";
			system ("PAUSE");
			exit(1);  //Argument 0 is a normal exit, any other value is an error exit.
		}
	}
}

CAccountsPayable::~CAccountsPayable()  //Destructor.
{

}

//************************************
// MAIN() FUNCTION.
//************************************
int main(int argc, char* argv[])
{
	int	 choice   =	0;
	bool	exit	 =	false;
	//************************************
	
	CAccountsPayable OPencil;

	do
	{
		OPencil.m_CreateSequentialFile();
		OPencil.m_ReadSequentialFile();
		
		//************************************
		system( "CLS" );
		cout << endl << endl << endl;
		cout << "  Type the number 1 and press return ";
		cout << "to run the program again.  " << endl << endl;
		cout << "  Type 0 and press return to exit. ==> ";
		cin >> choice;
		if ( choice == 0 )
		{
			EXIT_SUCCESS;
		}
		if ( choice == 1 )
			exit = false;
		else
		{
			exit = true;
		}
	}while( exit == false );

	OPencil.~CAccountsPayable(); 

	return EXIT_SUCCESS;
}




//**************************************
//C++ Beginner File Processing Tutorial
//Random Access File
//**************************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fixed;
using std::exit;
using std::ifstream;
using std::ios;
using std::left;
using std::right;
using std::ofstream;
using std::ostream;
using std::setw;
using std::showpoint;
using std::setprecision;
using std::string;

#endif  //CALC_ERROR_H

class CAccountsPayable
{
	public:

	   //Constructor.
	   CAccountsPayable( int = 0, string = "", string = "", double = 0.0 );  

	   //Accessor function for account number.
	   void m_SetAccountNumber( int );
	   int  m_GetAccountNumber( ) const;

	   //Accessor function for last name.
	   void m_SetLastName( string );
	   string m_GetLastName( ) const;

	   //Accessor function for first name.
	   void m_SetFirstName( string );
	   string m_GetFirstName( ) const;

	   //Accessor function for balance.
	   void m_SetBalance( double );
	   double m_GetBalance( ) const;

	   //Destructor.		
	   ~CAccountsPayable();

	private:

		int	accountNumber;
		char   lastName[ 15 ];
		char   firstName[ 10 ];
		double balance;
};

//************************************
//Constructor
//************************************	
CAccountsPayable::CAccountsPayable(int accountNumberValue,
	string lastNameValue, string firstNameValue, double balanceValue )
{
	m_SetAccountNumber( accountNumberValue );
	m_SetLastName( lastNameValue );
	m_SetFirstName( firstNameValue );
	m_SetBalance( balanceValue );
}

//************************************
//Get account number value.
//************************************
int  CAccountsPayable::m_GetAccountNumber( ) const
{
	return accountNumber;
}

//************************************
//Set account number value.
//************************************
void CAccountsPayable::m_SetAccountNumber( int accountNumberValue )
{
	accountNumber = accountNumberValue;
}

//************************************
//Get last name value.
//************************************
string  CAccountsPayable::m_GetLastName( ) const
{
	return lastName;
}

//************************************
//Set last name value.
//************************************
void CAccountsPayable::m_SetLastName( string lastNameString )
{
	const char *lastNameValue = lastNameString.data();
	int length = lastNameString.size();
	length = ( length < 15 ? length : 14 );
	strncpy_s( lastName, lastNameValue, length );
	lastName[ length ] = '\0';
}

//************************************
//Get first name value.
//************************************
string  CAccountsPayable::m_GetFirstName( ) const
{
	return firstName;
}

//************************************
//Set first name value.
//************************************
void CAccountsPayable::m_SetFirstName( string firstNameString )
{
	const char *firstNameValue = firstNameString.data();
	int length = firstNameString.size();
	length = ( length < 10 ? length : 9 );
	strncpy_s( firstName, firstNameValue, length );
	firstName[ length ] = '\0';
}

//************************************
//Get balance value.
//************************************
double CAccountsPayable::m_GetBalance( ) const
{
	return balance;
}

//************************************
//Set balance value.
//************************************
void CAccountsPayable::m_SetBalance( double balanceValue )
{
	balance = balanceValue;
}

//************************************
//Destructor
//************************************
CAccountsPayable::~CAccountsPayable()  
{

}

//************************************
// MAIN() FUNCTION.
//************************************
int main(int argc, char* argv[])
{
	int	 choice	=	0;
	bool	exitt	 =	false;
	//************************************
		
	do
	{
		system("CLS");
		cout << endl << endl << endl;
		cout << "	C++ Beginner File Processing Tutorial   "  << endl << endl;
		cout << "   ---------------------------------------  "  << endl << endl;
		cout << "	0  Quit, exits program.				 "  << endl << endl;
		cout << "	1  Create Random Access File:		   "  << endl;
		cout << "	   Writes Fixed Length Records To File  "  << endl << endl;
		cout << "	2  Write To Random Access File		  "  << endl << endl;
		cout << "	3  Read Random Access File Sequentially "  << endl << endl << endl;
						
		cout << endl << endl;
		cout << "	Please type a number from 0 to 3 " << endl << endl;
		cout << "	then press Enter ==> ";

		cin >> choice;

		switch(choice)	//start switch
		{
			case (0):
				exitt	 =	true;
				return EXIT_SUCCESS;
				break;

			case (1):
			//************************************
			//Writes fixed length records to
			//random access file.
			//************************************
			{
				ofstream outAccountsPayable( "AccountsPayable.dat",
				ios::out | ios::binary );

				if ( !outAccountsPayable )
				{
					system("CLS");
					cout << endl << endl << endl;
					cerr << "  File could not be opened." << endl;
					cout << endl << endl << endl;
					cout << "  ";
					system("PAUSE");
					exit( 1 );

					//Instantiates object OBlankAccountsPayable of type CAccountsPayable.
					CAccountsPayable OBlankAccountsPayable;

					for ( int i = 0; i < 100; i++ )
					{
						outAccountsPayable.write( reinterpret_cast
						< const char * > ( &OBlankAccountsPayable ),
						sizeof ( CAccountsPayable ) );
					}
				}
			system("CLS");
			cout << endl << endl << endl;
			cout << "  Congratulations you successfully created a random access file! " << endl << endl << endl;
			cout << endl << endl << endl;
			cout << "  ";
			system ("PAUSE");

			}
			//************************************
				break;

			case (2):
			//************************************
			//Writes to the random access file.
			//************************************
			{
				int	accountNumber;
				char   lastName[ 15 ];
				char   firstName[ 10 ];
				double balance;

				fstream outAccountsPayable( "AccountsPayable.dat",
				ios::in | ios::out |ios::binary );
				
				if ( !outAccountsPayable )
				{
					system("CLS");
					cout << endl << endl << endl;
					cerr << "  File could not be opened." << endl;
					cout << endl << endl << endl;
					cout << "  ";
					system("PAUSE");
					exit( 1 );
				}

				system("CLS");
				cout << endl << endl << endl;
				cout << "  Please enter customer account number." << endl << endl;
				cout << "  Enter a number from 1 to 100 " << endl << endl;
				cout << "  then press Enter => ";

				//Instantiates object OCustomer of type CAccountsPayable.
				CAccountsPayable OCustomer;

				cin >> accountNumber;
				cout << endl << endl << endl;
				cout << "  You entered " << accountNumber;
				cout << endl << endl << endl;
				cout << "  ";
				system ("PAUSE");

				if( accountNumber > 0 && accountNumber <= 100 )
				{
					system( "CLS" );
					cout << endl << endl << endl;
					cout << "  Please enter customer last name." << endl << endl;
					cout << "  Maximum 15 characters, for example Jones" << endl << endl;
					cout << "  and then press Enter => ";
					cin  >> setw( 15 ) >> lastName;
					cout << endl << endl << endl;
					cout << "  You entered " << lastName;
					cout << endl << endl << endl;
					cout << "  ";
					system ("PAUSE");

					system( "CLS" );
					cout << endl << endl << endl;
					cout << "  Please enter customer first name." << endl << endl;
					cout << "  Maximum 10 characters, for example Roy" << endl << endl;
					cout << "  and then press Enter => ";
					cin  >> setw( 10 ) >> firstName;
					cout << endl << endl << endl;
					cout << "  You entered " << firstName;
					cout << endl << endl << endl;
					cout << "  ";
					system ("PAUSE");

					system( "CLS" );
					cout << endl << endl << endl;
					cout << "  Please enter customer account balance." << endl << endl;
					cout << "  for example, 1000 " << endl << endl;
					cout << "  and then press Enter => ";
					cin  >> balance;
					cout << endl << endl << endl;
					cout << "  You entered " << balance;
					cout << endl << endl << endl;
					cout << "  ";
					system ("PAUSE");

					OCustomer.m_SetAccountNumber( accountNumber );
					OCustomer.m_SetLastName( lastName );
					OCustomer.m_SetFirstName( firstName );
					OCustomer.m_SetBalance( balance );

					outAccountsPayable.seekp( ( OCustomer.m_GetAccountNumber( ) - 1 ) *
						sizeof( CAccountsPayable ) );

					outAccountsPayable.write( reinterpret_cast< const char * > ( &OCustomer ),
						sizeof( CAccountsPayable ) );
				}
			}
			//************************************
				break;

			case (3):
			//************************************
			//Read random access file sequentially.
			//************************************
			{
				ifstream inAccountsPayable( "AccountsPayable.dat",
				ios::in | ios::binary );
				
				if ( !inAccountsPayable )
				{
					system("CLS");
					cout << endl << endl << endl;
					cerr << "  File could not be opened." << endl;
					cout << endl << endl << endl;
					cout << "  ";
					system("PAUSE");
					exit( 1 );
				}

				cout << left << setw( 10 ) << "Account"
					 << setw ( 16 ) << "Last Name" << left 
					 << setw ( 11 ) << "First Name"
					 << setw ( 10 ) << right << "Balance" << endl;

				//Instantiates object OCustomer of type CAccountsPayable.
				CAccountsPayable OCustomer;

				inAccountsPayable.read( reinterpret_cast< char * >
					( &OCustomer ), sizeof( CAccountsPayable ) );

				while ( inAccountsPayable && !inAccountsPayable.eof() )
				{
					if ( OCustomer.m_GetAccountNumber() != 0 )
					{
						   system("CLS");
						   cout << endl << endl << endl;
						   cout << "  ";

					  cout << left << setw( 10 ) << OCustomer.m_GetAccountNumber()
						   << setw ( 16 ) << OCustomer.m_GetLastName() << left 
						   << setw ( 11 ) << OCustomer.m_GetFirstName()
						   << setw ( 10 ) << setprecision( 2 ) << right << fixed
						   << showpoint << OCustomer.m_GetBalance() << endl; 

						   cout << endl << endl << endl;
						   cout << "  ";
						   system("PAUSE");
					}
				
					inAccountsPayable.read( reinterpret_cast< char * >
						( &OCustomer ), sizeof( CAccountsPayable ) );
				}
					
			}
			//************************************	
				break;

			default:
				cout << endl << endl << endl;
				cout << "Switch default error message! ";
				cout << endl << endl << endl;
				system("PAUSE");
				break;
		}

   	}while( exitt == false );

	return EXIT_SUCCESS;
}



• III. VOCABULARY

1. What is a bit?

A bit is a binary digit that can assume one of two values, 0 or 1. A bit is the smallest data item supported by computers.

2. What is a byte?

A byte is eight bits.

3. What is a character?

Digits, letters, and special symbols are referred to as characters.

4. What is a field?

A field is composed of characters that convey some meaning.

5. What is a record?

A record is represented as a class in C++ and is composed of fields called data members in C++.

6. What is a file?

Files you create with your editor are called source files. Most C++ compilers do not care what extension you give your source file, .cpp is normally the default. After your source file is compiled an object file is produced with an .obj or .o extension, C++ executable .exe extension programs are created by linking one or more object files with one or more libraries. Libraries are linkable files supplied with your compiler.

The files we will be discussing in this tutorial are the text files and binary files that store data so it can be retrieved for processing when needed.
A storage file is a group of related records. C++ views each file as a sequence of bytes. When a file is opened an object is created and a stream is associated with that object. If the file can support position requests, opening the file also initializes the file position indicator to the start of the file. To perform file processing in C++, header files <iostream> and <fstream> must be included to provide communications between a program and a file or device.

Standard input, standard output, and standard error output are three files that are connected to the console and opened automatically when a program is started. The file pointers stdin, stdout, and stderr are also automatically provided for these three files respectively.

7. What is a record key?

A record key uniquely identifies a record.

8. What is a database?

A group of related files are stored in a database.

9. What is a Database Management System (DBMS)?

A DBMS is a collection of programs designed to create and manage a database.

• IV. CREATING A SEQUENTIAL FILE

Step 1 Create A Stream:

Before you can use the member functions of a class in your program you have to create a stream by instantiating or declaring an object of that class in your program. The class for output is ofstream. You can use any object name you want to use.

The syntax for instantiating an object of the ofstream class is as follows:
ofstream object_name;

Step 2 Associate Or Link That Object With A File

After you create a stream by instantiating an object of the class in your program you have to associate or link that object with a file. You can use the open() function to associate the instantiated object with a file.
The complete detailed syntax for the prototype of an output file is as follows:

void ofstream::open(const char *filename, ios::openmode mode = ios::out | ios::trunc);

When the ofstream object is instantiated and associated with a file the ofstream object’s constructor opens the file.

After the stream object is associated with a file, the file can be used the same as any other stream object.

The portion of the attached example program relating to creating a sequential file is as follows:

[code]
//************************************
//Creates a sequential file.
//************************************  

Is This A Good Question/Topic? 0
  • +

Page 1 of 1