0

バイナリ ファイル ("example.dat") を逆方向に読み取ろうとして、レコードの構造体にその内容を入力しようとしています。ファイルには 10 個のレコードが含まれており、各レコードには 3 つのデータ型があります。

#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;
}

/* ヘルプとフィードバックをお待ちしております。*/

4

1 に答える 1

1

たとえば、金利などでなぜこのような奇妙な数値が得られるのか、私にはわかりません。ただし、すべてのエントリで同じ値が得られる理由は、行が

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

の最初のエントリを常に出力しdetailsます。次のように変更した場合:

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

に記録された実際の値が出力されdetailsます。


これは、配列の識別子が配列の最初の要素へのポインターとして動作するためです。さらに、このポインターでポインター演算を実行できます。したがって、次の 2 つのステートメントは同等です。

details + i
&details[i]
// This last one is just for fun, but is actually also equivalent to the other two.
&[i]details
于 2014-09-28T06:11:09.417 に答える