c_-_c_files:randomly_accessed_file
C - C++ Files - Randomly Accessed File
#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; }
c_-_c_files/randomly_accessed_file.txt · Last modified: 2020/07/15 09:30 by 127.0.0.1