c++structbinaryifstreamseekg

Populating a Struct with a Binary file


I am attempting to read a binary file ("example.dat") in reverse and populating a struct of records with its contents. The file contains 10 records, and each record has three data types.

#include <iostream>
#include <fstream>

using namespace std;

/* Gross Yearly Income */
const unsigned long int GYI = sizeof( unsigned long int );

/* Amortization Period in years as an unsigned integer */
const unsigned int APY = sizeof( unsigned int );

/* Year ly interest rate in double precision */
const double annualInterest = sizeof( double );

/*This is where I attempt to determine the size of the file and most likely a huge fail. */

/* Attempting to obtain file size */
const int RECORD_SIZE = GYI + APY + annualInterest;

/* There are ten records*/
const int RECORDS = 10;

struct record_t
{    
    unsigned long int grossAnnualIncome;
    unsigned int amortizationPeriod;
    double interestRate;

} total[RECORDS]; // a total of ten records

void printrecord (record_t *record);

int main()
{   
    record_t *details = new record_t[RECORDS];

    ifstream file; /* mortgage file containing records */

    file.open( "mortgage.dat", ios::binary );

/*This for loop is an attempt to read the .dat file and store the values found into the relevant    struct*/

    for ( int i = 0; i < RECORDS; i++)
    {           
        file.seekg( -( i + 1 ) * RECORD_SIZE, file.end);
        file.read( ( char * )( &details[i].grossAnnualIncome ), GYI );
        file.read( ( char * )( &details[i].amortizationPeriod ), APY );
        file.read( ( char * )( &details[i].interestRate ), annualInterest );    

        cout << i << " : " ; printrecord(details);
    }

    file.close();       

    return 0;       
}    

/* Display the file records according to data type */

void printrecord (record_t *record)
{
    cout << record -> grossAnnualIncome << endl;
    cout << record -> amortizationPeriod << endl;
    cout << record -> interestRate << endl;
}

/* Any help and feedback is appreciated. */


Solution

  • Why you get such strange number in for instance the interest-rate I cannot say I see. However, the reason you get the same values for every entry is because the line

    cout << i << " : " ; printrecord(details);
    

    Always prints the first entry in details. If you change it to:

    cout << i << " : " ; printrecord(details + i); 
    

    It will print the actual values recorded into details.


    The reason for this is that the identifier of an array will behave as a pointer to the first element of the array. Furthermore, you may do pointer-arithmetic on this pointer. Thus the following two statements are equivalent.

    details + i
    &details[i]
    // This last one is just for fun, but is actually also equivalent to the other two.
    &[i]details