简体   繁体   English

读写将结构写入二进制文件

[英]Read write a struct to binary files

The write/read is not giving the proper results. 写入/读取未给出正确的结果。

Can you please tell me why the second & third record is not displayed properly. 您能告诉我为什么第二条和第三条记录显示不正确吗?

Also how to know how many records a binary file contains? 另外如何知道一个二进制文件包含多少条记录?

Please see the code below 请看下面的代码

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

Output is get is as follows:- 得到的输出如下:

   00001
   20
   2
   1
   20
   ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠00001
   -858993460
   -858993460
   -858993460
   -1.07374e+008
   ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠00001
   -858993460
   -858993460
   -858993460
   -1.07374e+008
   Press any key to continue

You seem to write and read just one struct, but print 3. Last two are therefore garbage from stack. 您似乎只读写一个结构,但打印3。因此,最后两个是堆栈中的垃圾。

Additionally, it would be prudent to zero out at least ID , preferably entire struct, to avoid undefined bytes in disk file (uninitialised bytes of ID in this case), for example for your particular code in question: 另外,最好避免将至少ID (最好是整个结构)归零,以避免磁盘文件中未定义的字节(在这种情况下为ID未初始化字节),例如对于您所讨论的特定代码:

memset (dailytrans, 0, sizeof(dailytrans)); // this depends on dailytrans size being known at compile time

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM