【发布时间】:2014-09-28 05:15:32
【问题描述】:
我正在尝试反向读取二进制文件(“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;
}
/* 感谢任何帮助和反馈。 */
【问题讨论】:
-
那有什么问题?
-
每条记录的输出始终为 749126312092639282, 1814962227, 1.26773e+213
-
忽略您总是打印第一条记录的事实,1)您没有提供您编写文件的方式,以及 2)您是否验证了您编写的文件包含正确的数据。跨度>
-
很遗憾我没有写文件;这使得验证其内容变得困难
标签: c++ struct binary ifstream seekg