Contents  1-5  6-11  12-16  17-21  22-27   28-33  34 - 38  39-46  Projects   MFC

   Contact
   Search
   C
   C++
   Visual Basic
   Java
   JavaScript
   DHTML
   Style Sheets
   About
   Active X
   TDC Binding
   PHP
   Perl and CGI
   Flash
   XML
   SQL
   Messages
   Chat
   MCSE
   Linux
   Cabling   
   ActionScript
   Downloads
   E-Cards   
 
    
    

Binary files allow you to write an entire object with all of its data members to a file via pointers.  We could do this with
sequential files, provided our data could be stored in ASCII, but it would be a lot more work.  Instead of using the
parameters
ios::app or ios::in, we need to use ios::binary when opening a binary file for read or write
operations.  The ios parameters can also be "or'd" together using
||, thus combining them.  Thus, we could open a
binary file for appending with: 
ios::app||ios::binary.  Rather than using the stream operators with binary files, we will use:

write() - writes all the data at once of an entire data structure or object.  Syntax:  write((char*)&TheObject, sizeof TheObject);
read()-  reads all the data at once of an entire data structure or object.    Syntax: 
read((char*)&TheObject, sizeof TheObject));

Both of the functions above take a pointer to a char for the first argument, and the number of chars to write for the second argument.  This can be determined using the
sizeof() function.  Since the first argument is a pointer to a char, the address of the object must be passed in by using the addressOf operator, &.   I created the Employee class below for some of my database projects.  Let's see how an entire instance of the Employee class can be written to a file at once:

Example of writing an entire object to a binary file:

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

class Employee
{
   public:
     
//Overloaded Constructors
      Employee() { cout << "Employee object with no parameters created.\n"; }

      Employee(int ID, long social, double rate, int ag, long ph, string first, string last):
      EmpID(ID),
      SSN(social),
      HourlyRate(rate),
      age(ag),
      Phone(ph),
      FirstName(first),
      LastName(last)
    
      {  cout << "Employee with parameters created!\n";  }


      ~Employee() { cout << "Employee object destroyed.\n"; }

      int GetEmpID() const { return EmpID; }
      void SetEmpID(int ID) { EmpID = ID; }

      long GetSSN()const { return SSN; }
      void SetSSN(long social) { SSN = social; }

      double GetRate() { return HourlyRate; }
      void SetRate(double rate) { HourlyRate = rate; }

      int GetAge() { return age; }
      void SetAge(int ag) { age = ag; }

      long GetPhone() { return Phone; }
      void SetPhone(long ph) { Phone = ph; }

      string GetFirst() { return FirstName; }
      void SetFirst(string first) { FirstName = first; }

      string GetLast() { return LastName; }
      void SetLast(string last) { LastName = last; }
     
   private
:
      int EmpID;
      long SSN;
      double HourlyRate;
      int age;
      long Phone;
      string FirstName;
      string LastName;

};
//----------------------------------------------------------------------------------------------------------------------------
int main()
{
    char FileName[80];
    cout << "Please enter the file name: ";
    cin >> FileName;
    //Open filename user typed for binary write
    ofstream OutputFile(FileName, ios::binary);
    if(!OutputFile)
    {
         cout << "Unable to open " << FileName << " for writing.\n";
         return(1);  //returning one means an error occurred and ends the program
    }

    Employee CGermany(11, 725652145, 12.55, 34, 7544312, "Charles", "Germany");
    OutputFile.write((char*) &CGermany, sizeof CGermany);
    OutputFile.close();

      //Open filename user typed for binary read
    ifstream InputFile(FileName, ios::binary);
    if(!InputFile)
    {
        cout << "Unable to open " << FileName << " for reading.\n";
        return(1);
    }

    Employee EmpObject;
    InputFile.read((char*) &EmpObject, sizeof EmpObject);
    cout << endl << endl;
    cout << "Employee ID: " << EmpObject.GetEmpID() << endl;
    cout << "First Name: " << EmpObject.GetFirst() << endl;
    cout << "Last Name: " << EmpObject.GetLast() << endl;
    cout << "Social Sec #: " << EmpObject.GetSSN() << endl;
    cout << "Age: " << EmpObject.GetAge() << endl;
    cout << "Hourly Rate: " << EmpObject.GetRate() << endl;
    cout << "Phone: " << EmpObject.GetPhone() << endl;
    cout << endl << endl;
    InputFile.close();
    return 0;
}

All we had to do was code some accessor methods and something to display the values of Employee data members.  We could have placed the code for displaying all the data members into a member function, call it DisplayEmployeeInfo(), if you will, and simply called DisplayEmployeeInfo() each time we needed to view the contents of an object.  Now it's time to get creative and put on our critical thinking caps.  To make the above program more useful, modify and enhance it by the criteria below.  No more hints!  :)  Here's the assignment:

  • Put the whole program into a loop so it will keep running until it encounters a sentinel value

  • Create a dynamic array of Employee objects, so the program can search through them

  • Create search routines and methods to iterate through the Employee arrays and find data members

  • Allow the user to save multiple employee objects.

  • Instead of allowing the user to name each file, assign a primary, unique key to each object file.

Below, the Player class is listed, which I wrote for  some of my game projects to handle character objects.  Skip down until you see the functions SaveCharacter() and LoadCharacter().  An instance of the Player class has many, many data members associated with it.  Saving this information in a sequetial file would be tedious.  Yet by saving a Player object to a binary file, all of the data members that correspoond to a Player object can be saved at once.  Take a look at the process:

class Player
{
public:

        // Constructor
	Player() { 
	           name = "NewPlayerNow";
	           InitializeItems();
                   cout << "Player object created.\n";  }
        
        // Destructor 
	~Player() { cout << "\nPlayer character destroyed.\n"; }

	//Accessor Methods
        void setLevel(int lev) { level = lev; }
	int getLevel() { return level; }

	void setStrength(int str) { strength = str; }
	int getStrength() { return strength; }

	void setIntelligence(int intel) { intelligence = intel; }
	int getIntelligence() { return intelligence; }

	void setCharisma(int chrs) { charisma = chrs; }
	int getCharisma() { return charisma; }

	void setDexterity(int dex) { dexterity = dex; }
	int getDexterity() { return dexterity; }

	void setName(char na[15]) { 
		     name = new char[15];
		     strcpy(name, na);
	             cout << "\nCharacter name set to " << name << "."; }
	char * getName() { return name; }


        //Inventory Item Accessors
	void setSword(bool swd) { sword = swd; }
	bool getSword() { return sword; } 

	void setBow(bool lng) { longbow = lng; }
	bool getBow() { return longbow; }

	void setStaff(bool stf) { staff = stf; }
	bool getStaff() { return staff; }

	void setShield(bool shl) { shield = shl; } 
	bool getShield() { return shield; }

	void setArmor(bool arm) { armor = arm; }
	bool getArmor() { return armor; }

        void DisplayInventory() {
             cout << "You have the following items:\n";
             if(sword) { cout << " sword, "; }
             if(longbow) { cout << " longbow, "; }
             if(staff) { cout << " staff, "; }
             if(shield) { cout << " shield, "; }
             if(armor) { cout << " armor, "; }
             if(!sword && !longbow && !staff && !shield && !armor) { 
                cout << "\nIt appears that you have NOTHING!"
                cout << "\nAbsolutely nothing!\nHow sad..."; 
             }

        } //close DisplayInventory function
        //Game Cheat - gives all items
        void AllItems() {        
             sword = true;
             longbow = true;
             staff = true;
             shield = true;
             armor = true;
        }
        //Initialize Items
        void InitializeItems() {
             level = 1;
             strength = 10;
             intelligence = 18;
             charisma = 17;
             dexterity = 16;
             sword = false;
             longbow = false;
             staff = false;
             shield = false;
             armor = false;
        }

        //Save Character
        void SaveCharacter() {
	     char CharacterName[80];
	     cout << "Please enter a name for your character to save: ";
	     cin >> CharacterName;

             ofstream fout(CharacterName,ios::trunc||ios::binary);

	          if(!fout) { 
		     cout << "Unable to create " << CharacterName 
		          << " for writing.\n";
	          }  //close if

	     fout.write((char*) &*this,sizeof(*this));

	     fout.close();
        } //close save character function


        //Load Character
        void LoadCharacter() {
	     char CharacterName[80];
	     cout << "Please enter the name of your character to load: ";
	     cin >> CharacterName;
	     ifstream fin(CharacterName,ios::trunc||ios::binary);

	     if (!fin) {
		 cout << "Unable to find " << CharacterName << " for reading.\n";
	     }
	     fin.read((char*) &*this, sizeof(this));

	     fin.close();
	     cout << "Loaded player name is: " << name << ".\n";
	     cout << "Loaded player strength is: " << strength << ".\n";
             cout << "Loaded player level is: " << level << ".\n";
	     cout << "Loaded player intelligence is: " << intelligence << ".\n";
             cout << "Loaded player charisma is: " << charisma << ".\n";
	     cout << "Loaded player dexterity is: " << dexterity << ".\n";
	     DisplayInventory();
        } //close load character function

        // DisplayCharacter
        void DisplayCharacter() {
	     cout << "Player name is: " << name << ".\n";
	     cout << "Player strength is: " << strength << ".\n";
             cout << "Player level is: " << level << ".\n";
	     cout << "Player intelligence is: " << intelligence << ".\n";
             cout << "Player charisma is: " << charisma << ".\n";
	     cout << "Player dexterity is: " << dexterity << ".\n";
	     DisplayInventory();
        }

        // Display Menu
        void DisplayMenu() {
             bool quit = false;
             char choice;
             cout << "\nChoose an option:\n";
             cout << "***********MENU***********\n";
             cout << "*                        *\n";
             cout << "* L = Load player        *\n";
             cout << "* S = Save player        *\n";
             cout << "* D = Display player     *\n";
             cout << "* C = Change attributes  *\n";
             cout << "* I = Inventory          *\n";
             cout << "* A = All Items Cheat    *\n";
             cout << "* Q = Quit               *\n";
             cout << "*                        *\n";
             cout << "**************************\n";
             while(!quit) {
                   DisplayMenu();
                   cin >> choice;
                   
                   switch(choice) {
                        case 'l' : LoadCharacter(); break;
                        case 'L' : LoadCharacter(); break;
	                case 'd' : DisplayCharacter(); break; 
	                case 'D' : DisplayCharacter(); break;
	                case 's' : SaveCharacter(); break;
	                case 'S' : SaveCharacter(); break;
	                case 'c' : SetPlayerAttributesCheat(this); break;
	                case 'C' : SetPlayerAttributesCheat(this); break;
                        case 'i' : DisplayInventory(); break;
	                case 'I' : DisplayInventory(); break;
	                case 'a' : AllItems(); break;
	                case 'A' : AllItems(); break;
	                case 'q' : quit = true; break;
	                case 'Q' : quit = true; break;
                        default : cout << "Please choose either c, l, s, or d."
                                       << " (LSD - get it?) haha";
                   } //close switch statement

             } // close while true
        } //close function

    // Data Members
    private:
    int level;
    int strength;
    int intelligence;
    int charisma;
    int dexterity;
    char * name;
    //Items
    bool sword;
    bool longbow;
    bool staff;
    bool shield;
    bool armor;

}; 

 



©2004 C. Germany