我试图反向读取一个二进制文件(“ example.dat”),并用其内容填充记录的结构。该文件包含10个记录,每个记录具有三种数据类型。

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


/ *感谢您的帮助和反馈。 * /

最佳答案

为什么您得到如此奇怪的数字,例如我无法说出的利率。但是,您为每个条目获得相同值的原因是因为该行

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


始终打印details中的第一项。如果将其更改为:

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


它将打印记录在details中的实际值。



这样做的原因是,数组的标识符将充当指向数组第一个元素的指针。此外,您可以对此指针进行指针算术运算。因此,以下两个语句是等效的。

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

关于c++ - 用二进制文件填充结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26081875/

10-09 09:18
查看更多