2014-09-28 52 views
0

我正試圖讀取一個二進制文件(「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; 
} 

/*任何幫助和反饋意見。 */

+0

那麼問題是什麼? – 2014-09-28 05:23:44

+0

輸出始終 749126312092639282, 1814962227, 1.26773e + 213 對每條記錄 – aguilar 2014-09-28 05:28:25

+0

忽略你總是打印的第一條記錄的事實,1)你沒有提供你怎麼寫的文件,和2 )是否驗證了您寫入的文件是否包含正確的數據。 – PaulMcKenzie 2014-09-28 06:19:51

回答

0

爲什麼你會得到這樣奇怪的數字,例如我不能說我看到的利率。然而,之所以你會得到每個條目相同的值是因爲該行

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 
+0

我能夠通過將細節+ i添加到我的源代碼中來檢索前兩個記錄。非常感激。 – aguilar 2014-09-29 05:33:49

+0

很棒,如果你喜歡這個答案,可以隨時上傳或接受它。 :) – 2014-09-29 19:54:08