Writing to Binary Files - C++ File Stream

C++ examples for File Stream:Binary File

Description

Writing to Binary Files

Demo Code

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

 using namespace std; 

 class Employee /*  w  w  w . j  av  a2 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; 

  saveGame.CurrentLevel(3); 
  saveGame.CurrentScore(11042); 
  saveGame.PlayerName("Ozy mandius Jones"); 

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

     cout << "W riting save game info to file..."; 
     saveFile.write( 
         (char *)(&saveGame), 
          sizeof(Employee)); 
     cout << "Done." << endl; 
   } 



  return 0; 
}

Result


Related Tutorials