写/读没有给出正确的结果。
你能告诉我为什么第二和第三条记录没有正确显示吗?
另外如何知道二进制文件包含多少条记录?
请看下面的代码
#include <iostream.h>
#include <fstream.h>
#include <string.h>
enum Ticket_type { ADULT, CHILD, STUDENT, SENIOR, FREE, SPECIAL };
typedef struct transaction_stru
{
char ID[10];
int tariff;
Ticket_type tickettype;
int qty;
float total;
}transaction_t;
int main () {
// Attempt to open it for reading.
fstream fs("trans.dat", ios::in);
if (!fs)
fs.open("trans.dat", ios::out | ios::binary | ios::app);
else{
fs.close(); // File exists; close and reopen for write.
transaction_t dailytrans[3];
dailytrans[0] = {"00001", 20, STUDENT, 1, 20.00 };
dailytrans[1] = {"00002", 30, ADULT, 2, 60.00 };
dailytrans[2] = {"00003", 30, SPECIAL, 3, 30.00 };
fs.open("trans.dat", ios::out | ios::binary | ios::app);
fs.write((char*)&dailytrans,sizeof(dailytrans));
fs.close();
}
// Let us read the file now
fs.open("trans.dat", ios::in | ios::binary);
if(!fs){
cout << "Error Opening trans.dat";
//throw SomeFileException;
}
transaction_t results[3];
fs.read((char*)&results,sizeof(transaction_stru));
for (size_t i=0; i < 3; i++)
{
cout << results[i].ID << endl;
cout << results[i].tariff << endl;
cout << results[i].tickettype << endl;
cout << results[i].qty << endl;
cout << results[i].total << endl;
}
return 0;
}
输出得到如下: -
00001
20
2
1
20
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠00001
-858993460
-858993460
-858993460
-1.07374e+008
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠00001
-858993460
-858993460
-858993460
-1.07374e+008
Press any key to continue