Reading from Binary Files - C++ File Stream

C++ examples for File Stream:Binary File

Description

Reading from Binary Files

Demo Code

#include <cstdlib> 
  #include <iostream> 
  #include <string>   
  #include <fstream> 

  using namespace std; 

  class Employee 
  { /*from   ww w  . ja v a 2  s  .  c o m*/
  public : 
     Employee(); 

     void CurrentLevel(int levelNumber); 
     int CurrentLevel(); 

     void CurrentScore(int score); 
     int CurrentScore(); 

     void PlayerName(char name[80]); 
     std ::string PlayerName(); 

 private: 
     int currentLevel; 
     int currentScore; 
     char playerName[80]; 
}; 


Employee ::Employee() 
{ 
   currentLevel = 0; 
   currentScore = 0; 
} 

void Employee ::CurrentLevel(int levelNumber) 
{ 
   currentLevel = levelNumber; 
} 

int Employee ::CurrentLevel() 
{ 
    return (currentLevel); 
} 

void Employee ::CurrentScore(int score) 
{ 
    currentScore = score; 
} 

int Employee ::CurrentScore() 
{ 
   return (currentScore); 
} 

void Employee ::PlayerName(char name[80]) 
{ 
   strcpy (playerName, name); 
} 

std ::string Employee ::PlayerName() 
{ 
  return (playerName); 
} 

int main(int argc, char *argv []) 
{ 
   Employee saveGame; 

   cout << "Opening save game file..."; 
   ifstream saveFile; 
   saveFile.open("save.dat", ios::binary ); 
    if (saveFile.is_open()) 
    { 
       cout << "Done." << endl; 

       cout << "Reading save game info from file..."; 
       saveFile.read( 
           (char *)(&saveGame), 
            sizeof(Employee)); 
       cout << "Done." << endl; 

       cout << endl; 
       cout << "Player Name: " << saveGame.PlayerName(); 
       cout << endl; 
       cout << "Player Score: " << saveGame. CurrentScore(); 
      cout << endl; 
      cout << "Current Level: " << saveGame. CurrentLevel(); 
      cout << endl; 

      saveFile.close(); 
   } 


 
   return 0; 
 }

Result


Related Tutorials