簡體   English   中英

讀寫將結構寫入二進制文件

[英]Read write a struct to binary files

寫入/讀取未給出正確的結果。

您能告訴我為什么第二條和第三條記錄顯示不正確嗎?

另外如何知道一個二進制文件包含多少條記錄?

請看下面的代碼

  #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

您似乎只讀寫一個結構,但打印3。因此,最后兩個是堆棧中的垃圾。

另外,最好避免將至少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