Creating a randomly accessed file : binary file « File Stream « C++ Tutorial






#include <iostream>
using std::cerr;
using std::endl;
using std::ios;

#include <fstream>
using std::ofstream;

#include <cstdlib>
using std::exit;

#include <string>
using std::string;

class Account
{
public:
    Account( int accountNumberValue, string lastNameValue, string firstNameValue, double balanceValue )
    {
       setAccountNumber( accountNumberValue );
       setLastName( lastNameValue );
       setFirstName( firstNameValue );
       setBalance( balanceValue );
    }

    int getAccountNumber() const
    {
       return accountNumber;
    }
    void setAccountNumber( int accountNumberValue )
    {
       accountNumber = accountNumberValue; // should validate
    }
    string getLastName() const
    {
       return lastName;
    }
    void setLastName( string lastNameString )
    {
       const char *lastNameValue = lastNameString.data();
       strncpy( lastName, lastNameValue, 5 );
       lastName[ 5 ] = '\0';
    }

    string getFirstName() const
    {
       return firstName;
    }

    void setFirstName( string firstNameString )
    {
       const char *firstNameValue = firstNameString.data();
       strncpy( firstName, firstNameValue, 5 );
       firstName[ 5 ] = '\0';
    }
    double getBalance() const
    {
       return balance;
    }
    void setBalance( double balanceValue )
    {
       balance = balanceValue;
    }

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

int main()
{
   ofstream outCredit( "credit.dat", ios::binary );

   if ( !outCredit )
   {
      cerr << "File could not be opened." << endl;
      exit( 1 );
   }

   Account blankClient(1,"AAAAA","BBBBB",1.2);

   // output 100 blank records to file
   for ( int i = 0; i < 100; i++ )
      outCredit.write( reinterpret_cast< const char * >( &blankClient ),
         sizeof( Account ) );

   return 0;
}








12.3.binary file
12.3.1.Open a binary file
12.3.2.Reading binary file
12.3.3.Open a binary file and read
12.3.4.Output a binary file in hexadecimal
12.3.5.Write Unformatted Binary Data to a File
12.3.6.Use read() to input blocks of binary data.
12.3.7.Use write() to output a block of binary data.
12.3.8.Creating a randomly accessed file
12.3.9.Append to a binary file
12.3.10.Unformatted and Binary I/O