我正試圖讀取一個二進制文件(「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;
}
/*任何幫助和反饋意見。 */
那麼問題是什麼? – 2014-09-28 05:23:44
輸出始終 749126312092639282, 1814962227, 1.26773e + 213 對每條記錄 – aguilar 2014-09-28 05:28:25
忽略你總是打印的第一條記錄的事實,1)你沒有提供你怎麼寫的文件,和2 )是否驗證了您寫入的文件是否包含正確的數據。 – PaulMcKenzie 2014-09-28 06:19:51