This content is not currently approved and is visible here for review only.

Library code snippets

[C++] File interaction with structures

Code Sample

 

 

=> Download the following code in this file : Employee_Record.cpp (12KB)

 

/***
//// Last Build : 8_19_08
//// Compiler   : VS2005
//// Programmer : Mohammad Rastkar
//// Capability : Implementing a variable size record.
//// Function   : add, delete, modify, display records ( hourly or salaried )
***/

 

/////////////     Includes    /////////////
 
#include <cstdlib> // system()
#include <conio.h> // getch()
#include <fstream>
#include <sys\stat.h> // stat(status of a file)
#include <iostream>
using namespace std;
 
 
/////////////     Data types    /////////////
 
enum { SALARIED = '0', HOURLY = '1' };
 
struct Employee_Record // Employee record
{
      char PAY_TYPE; // Tag_Field : "SALARIED = 0, HOURLY = 1"
     
      union
      {
            struct //// SALARIED
            {
                  double MONTHLY_RATE;
                  int    START_DATE;
            };
 
            struct //// HOURLY
            {
                  double RATE_PER_HOUR;
                  int    REG_HOURS;
                  int    OVERTIME_HOURS;
            };
      };
 
      int ID;
      int AGE;
      char DEPT;
      bool deleted;
};
 
 
/////////////     Variable Declarations & Constants /////////////
 
#define EMPLOYEE_FILE_NAME "Employees.txt" // name of the database file to store employees informations
 
Employee_Record Employee;
char     choice; // for choice in menu
fstream *fs = NULL, *fs1 = NULL;// file streams for files : fs -> 'Employee', fs1 -> 'temp'
bool     deletion = false; // if any record has been deleted
 
 
/////////////     Function Prototypes    /////////////
 
void closeFile(fstream *); // closes a file with its pointer, then deletes the file pointer
bool isFileExist(const char *); // check if a file exists
 
 
/////////////     Main    /////////////
int main()
{
      while (true)
      {
            do ////// Menu //////
            {
                  system( "cls" ); // clear screen
                       
                  cout << "\n    < Employees Database > \n\n";
                  cout << "(1) Add     a new Record \n";
                  cout << "(2) Modify an existing Record\n";
                  cout << "(3) Delete an existing Record \n";               
                  cout << "(4) Display Records \n";
                  cout << "(5) Exit \n\n";
                  cout << " Enter a choice (1-5) : " << flush;
                  choice = getch();
            } while ( choice < '1' || choice > '5'); // while we have no good(between 1 and 5), show menu again
 
            system( "cls" );
 
            // to modify, delete or display records, database file should exist, then we have some records           
            if (choice == '2' || choice == '3' || choice == '4')
            {
                  if (!isFileExist(EMPLOYEE_FILE_NAME)) // if database file doesn't exist
                  {
                        cout << "\n Database file ('" << EMPLOYEE_FILE_NAME << "') doesn't exist, then there are no records." << endl;
                        system("pause");
                        continue; // show the menu again
                  }
            }
 
            switch ( choice )
            {
            int recs_num; // number of records before the record for modifying(deletion)
            int id;
 
            case '1' : ////// Add Record //////
 
                  cout << "\n\t\t < Entering a new record > ";
                  cout << "\n   Enter the following informations for the new record : ";
                  cout << "\n\n PAY_TYPE ( SALARIED : 0, HOURLY : 1 ) : ";
                  cin >> Employee.PAY_TYPE;
 
                  cout << "\n ID : ";
                  cin >> Employee.ID;
                  cout << "\n AGE : ";
                  cin >> Employee.AGE;
                  cout << "\n DEPT (one character) : ";
                  cin >> Employee.DEPT;
 
                  if ( Employee.PAY_TYPE == SALARIED )
                  {
                        cout << "\n MONTHLY_RATE : ";
                        cin >> Employee.MONTHLY_RATE;
                        cout << "\n START_DATE : ";
                        cin >> Employee.START_DATE;
                  }
 
                  if ( Employee.PAY_TYPE == HOURLY )
                  {
                        cout << "\n RATE_PER_HOUR : ";
                        cin >> Employee.RATE_PER_HOUR;
                        cout << "\n REG_HOURS : ";
                        cin >> Employee.REG_HOURS;
                        cout << "\n OVERTIME_HOURS : ";
                        cin >> Employee.OVERTIME_HOURS;
                  }
 
                  Employee.deleted = 0;
 
                  fs = new fstream( EMPLOYEE_FILE_NAME, ios::out | ios::app | ios::binary );
 
                  if (!fs)
                  {
                        cout << "\n Can't open or create '" << EMPLOYEE_FILE_NAME << "' file" << endl;
                        system("pause");
                        break;
                  }
                 
                  fs->write( (char *) &Employee, sizeof(Employee) );
                             
                  closeFile(fs);
 
                  cout << "\n Record added." << endl;
                  system("pause");
                 
                  break;
 
            case '2' : ////// Modify Record //////
 
                  cout << "\n Enter employee ID, that you want modify its informatin : ";
                  cin >> id;
 
                  fs = new fstream( EMPLOYEE_FILE_NAME, ios::in | ios::out | ios::binary );
 
                  if (!fs)
                  {
                        cout << "\n Can't open or create '" << EMPLOYEE_FILE_NAME << "' file" << endl;
                        system("pause");
 
                        break;
                  }
                 
                  recs_num = -1;
 
                  while (fs->read( (char *) &Employee, sizeof(Employee) ))
                  {
                        recs_num++;
 
                        if ( Employee.ID == id && !Employee.deleted)
                              break;
                  }
 
                  if (fs->eof()) // if (the record is not in the file || it's there but it's deleted)
                  {
                        cout << "\n Your specified employee doesn't exist in file." << endl;
                        closeFile(fs);
                        system("pause");
                        break;
                  }
 
 
                  cout << "\n   Enter new informations for this record : ";
                  cout << "\n\n PAY_TYPE ( SALARIED : 0, HOURLY : 1 ) : ";
                  cin >> Employee.PAY_TYPE;
 
                  cout << "\n ID : ";
                  cin >> Employee.ID;
                  cout << "\n AGE : ";
                  cin >> Employee.AGE;
                  cout << "\n DEPT (one character) : ";
                  cin >> Employee.DEPT;
 
                  if ( Employee.PAY_TYPE == SALARIED )
                  {
                        cout << "\n MONTHLY_RATE : ";
                        cin >> Employee.MONTHLY_RATE;
                        cout << "\n START_DATE : ";
                        cin >> Employee.START_DATE;
                  }
 
                  if ( Employee.PAY_TYPE == HOURLY )
                  {
                        cout << "\n RATE_PER_HOUR : ";
                        cin >> Employee.RATE_PER_HOUR;
                        cout << "\n REG_HOURS : ";
                        cin >> Employee.REG_HOURS;
                        cout << "\n OVERTIME_HOURS : ";
                        cin >> Employee.OVERTIME_HOURS;
                  }
                 
 
                  fs->seekp ( sizeof(Employee) * recs_num, ios::beg ); // go to the first of the record to be modified
                  fs->write( (char *) &Employee, sizeof(Employee) );
                 
                  closeFile(fs);
 
                  cout << "\n Record is modified." << endl;
                  system("pause");
 
                  break;
 
 
            case '3' : ////// Delete Record //////
 
                  cout << "\n Enter employee's ID, for deletion : ";
                  cin >> id;
 
                  fs = new fstream( EMPLOYEE_FILE_NAME, ios::in | ios::out | ios::binary );
 
                  if (!fs)
                  {
                        cout << "\n Can't open or create '" << EMPLOYEE_FILE_NAME << "' file." << endl;
                        system("pause");
                        break;
                  }
                 
                  recs_num = -1;
 
                  while (fs->read( (char *) &Employee, sizeof(Employee) ))
                  {
                        recs_num++;
 
                        if ( Employee.ID == id && !Employee.deleted ) // if user deleted an employee then added another one with the same ID in the same instance of program runs, deleted employee is still there, then we should go through all the file
                              break;
                  }
 
                  if (fs->eof()) // if (the record is not in the file || it's there but it's deleted)
                  {
                        cout << "\n Your specified employee doesn't exist in database file." << endl;
                        closeFile(fs);
                        system("pause");                   
                        break;
                  }
 
                  Employee.deleted = 1;
 
                  fs->seekp ( sizeof(Employee) * recs_num, ios::beg );
                  fs->write( (char *) &Employee, sizeof(Employee) );
                 
                  closeFile(fs);
 
                  deletion = true; // we have some deleted records
 
                  cout << "\n Record is deleted." << endl;
                  system("pause");
 
                  break;
 
 
            case '4' : // Display Records
 
                  ////// Print Salaried records...
                  fs = new fstream( EMPLOYEE_FILE_NAME, ios::in | ios::binary );
 
                  if (!fs)
                  {
                        cout << "\n Can't open or create '" << EMPLOYEE_FILE_NAME << "' file." << endl;
                        system("pause");
                        break;
                  }
 
                  // display column titles
                  cout << "\n\t\t < Salaried >\n\n";
                  cout << "ID\tAGE\tDEPT\tMONTHLY_RATE\tSTART_DATE\n"
                         << "-------------------------------------------------- \n";                                         
                                   
                  while (fs->read( (char *) &Employee, sizeof(Employee) )) // display records
                  {
                        if ( Employee.PAY_TYPE == SALARIED && !Employee.deleted )
                        {
                              cout << Employee.ID << '\t';
                              cout << Employee.AGE << '\t';
                              cout << Employee.DEPT << '\t';
                              cout << Employee.MONTHLY_RATE << "\t\t";
                              cout << Employee.START_DATE   << '\n';
                        }
                  }
 
                  cout << "\n To see Hourly records, "; system("pause");
 
                  closeFile(fs);
 
                  ////// Print Hourly records...                 
                  system( "cls" );
 
                  fs = new fstream( EMPLOYEE_FILE_NAME, ios::in | ios::binary );
 
                  if (!fs)
                  {
                        cout << "\n Can't open or create '" << EMPLOYEE_FILE_NAME << "' file." << endl;
                        system("pause");
                        break;
                  }
                 
                  cout << "\n\t\t\t < Hourly > \n\n";
                  cout << "ID\tAGE\tDEPT\tRATE_PER_HOUR\tREG_HOURS\tOVERTIME_HOURS\n"
                         << "---------------------------------------------------------------------- \n";
 
                  while ( fs->read( (char *) &Employee, sizeof(Employee_Record) ) )
                  {
                        if ( Employee.PAY_TYPE == HOURLY && !Employee.deleted )
                        {
                              cout << Employee.ID << '\t';
                              cout << Employee.AGE << '\t';
                              cout << Employee.DEPT << '\t';
                              cout << Employee.RATE_PER_HOUR << "\t\t";
                              cout << Employee.REG_HOURS      << "\t\t";
                              cout << Employee.OVERTIME_HOURS << '\n';
                        }
                  }
                 
                  cout << "\n To see menu, "; system("pause");
 
                  closeFile(fs);
 
                  break;
                 
 
            case '5' : // Exit
 
                  if (deletion) // if there is any deletion, then update database file (create a new temp file that doesn't have deleted records, then remove the old database file and rename temp file to database file name)
                  {
                        cout << "\n Updating '" << EMPLOYEE_FILE_NAME << "' File..." << endl;
 
                        fs = new fstream( EMPLOYEE_FILE_NAME, ios::in | ios::binary );
                        if (!fs)
                        {
                              cout << "\n Can't open '" << EMPLOYEE_FILE_NAME << "' file, then Updating is incomplete." << endl;
                              system("pause");
 
                              system( "cls" );
                              return 1;
                        }
 
                        fs1 = new fstream( "temp", ios::out | ios::binary);
                        if (!fs1)
                        {
                              cout << "\n Can't create temp file, then Updating is incomplete." << endl;
                              system("pause");
 
                              closeFile(fs);
                              system( "cls" );
                              return 1;
                        }
 
                        // write nondeleted records to the temp file
                        while (fs->read( (char *) &Employee, sizeof(Employee) ))
                              if ( !Employee.deleted )
                                    fs1->write( (char *) &Employee, sizeof(Employee) );
 
                        closeFile(fs);
                        closeFile(fs1);
 
                      if( remove( EMPLOYEE_FILE_NAME ) == -1 ) // if there is an error
                        {
                            cout << "\n Can't delete '" << EMPLOYEE_FILE_NAME << "' file, then Updating is incomplete." << endl;
                              system("pause");
                             
                              system( "cls" );
                              return 1;
                        }
                       
                       
                        struct stat st; // to check size of the temp file
                        int res = stat( "temp", &st );
                       
                        if (st.st_size == 0) // if all of records are deleted then the temp file size is zero                        
                              remove( "temp" ); // we have no records, then no database file is needed, just delete the temp file
                        else
                              if ( rename ("temp", EMPLOYEE_FILE_NAME) )
                              {
                                    cout << "\n Can't rename temp file, then Updating is incomplete." << endl;
                                    system("pause");
                                   
                                    system( "cls" );
                                    return 1;
                              }
 
                        cout << "\n Updating database file completed." << endl;
                        system("pause");
                  }
 
                  system( "cls" );
                  return 0;
 
                  break;
            } // end 'switch'
      } // end 'while'
 
      return 0;
} // end 'main()'
 
 
/////////////     Function Definitions    /////////////
 
void closeFile(fstream *fs)
{
      fs->close(); // close the file
      delete fs;
      fs = NULL;
}
 
 
bool isFileExist(const char * file_name)
{    
      struct stat st; // to check status of file
      int res = stat( file_name, &st );
      return (res == 0); // if file exists     
}

Comments

  1. 01 Jan 1999 at 00:00

    This thread is for discussions of [C++] File interaction with structures.

Leave a comment

Sign in or Join us (it's free).

AddThis

Related discussion

Events coming up

  • Dec 6

    Developing AJAX Web Applications with Castle Monorail

    London, United Kingdom

    Monorail is the model-view-controller engine of the Castle Project, bringing many of the best ideas of Ruby on Rails to the .NET world. In this talk, David De Florinier and Gojko Adzic show how Monorail makes it easy to develop .NET based AJAX applications, and how to use the Castle Project to build Web 2.0 applications effectively. Come to this session if you are a .NET web developer. Everyone is welcome!