Advertisement
avr39ripe

cppBinFilesAdvanced

Nov 8th, 2021
797
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <chrono>
  4.  
  5. struct Temp
  6. {
  7.     int id;
  8.     double temperature;
  9.     char desc[20];
  10. };
  11.  
  12. int main()
  13. {
  14.     const int tempsSize{ 3 };
  15.     Temp temps[tempsSize]{
  16.         {1, 0,"ice"},
  17.         {2, 100.0, "boil"},
  18.         {3, 26.6, "comfort"}
  19.     };
  20.  
  21.  
  22.     std::fstream iofile;
  23.  
  24.     iofile.open("d:\\temp.dat", std::ios::trunc | std::ios::out | std::ios::in | std::ios::binary);
  25.  
  26.     if ( !iofile)
  27.     {
  28.         std::cout << "IOERROR: can't create/open file!\n";
  29.         return 1;
  30.     }
  31.  
  32.     for (int i{ 0 }; i < tempsSize; ++i)
  33.     {
  34.         iofile.write((char*)&(temps[i].id), sizeof(int));
  35.         iofile.write((char*)&(temps[i].temperature), sizeof(double));
  36.         iofile.write((char*)&(temps[i].desc), 20);
  37.     }
  38.  
  39.     const int recordSize{ sizeof(int) + sizeof(double) + 20 };
  40.  
  41.     iofile.seekg(recordSize * 1, std::ios::beg);
  42.  
  43.     Temp fix{ 4, 100500.424242, "kipitok" };
  44.  
  45.     iofile.write((char*)&(fix.id), sizeof(int));
  46.     iofile.write((char*)&(fix.temperature), sizeof(double));
  47.     iofile.write((char*)&(fix.desc), 20);
  48.  
  49.     iofile.seekg(0, std::ios::beg);
  50.  
  51.     Temp readTemps[tempsSize]{};
  52.     int idx{ 0 };
  53.  
  54.     while (!iofile.eof())
  55.     {
  56.         iofile.read((char*)&(readTemps[idx].id), sizeof(int));
  57.         iofile.read((char*)&(readTemps[idx].temperature), sizeof(double));
  58.         iofile.read((char*)&(readTemps[idx].desc), 20);
  59.         if (iofile.fail())
  60.         {
  61.             break;
  62.         }
  63.  
  64.         std::cout << "Temps #" << readTemps[idx].id << ' '
  65.             << readTemps[idx].temperature << ' '
  66.             << readTemps[idx].desc << '\n';
  67.         ++idx;
  68.     }
  69.  
  70.     iofile.close();
  71.  
  72.     return 0;
  73. }  
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement