Advertisement
Guest User

Untitled

a guest
Sep 19th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <fstream>
  2. #include <string>
  3. #include <iostream>
  4. #include <stdlib.h>
  5.  
  6. using namespace std;
  7.  
  8. struct MyStruct
  9. {
  10.     float a,b,c;
  11.     int d;
  12.     char msg[256];
  13. };
  14.  
  15. void print_struct( MyStruct *s )
  16. {
  17.     std::cout << "a,b,c :" << s->a << ", " << s->b << ", " << s->c << endl;
  18.     std::cout << "d :" << s->d << endl;
  19.     std::cout << "msg :" << s->msg << endl;
  20.    
  21. }
  22.  
  23. void save()
  24. {
  25.     std::ofstream fout("struct.dat", std::ios::binary);
  26.     if(fout.bad())
  27.     {
  28.             fout.close();
  29.             return;
  30.     }
  31.    
  32.     MyStruct mydata;
  33.     mydata.a = 3.14159;
  34.     mydata.b = 6.28;
  35.     mydata.c = 2.73;
  36.     mydata.d = 42;
  37.     // Format a string...
  38.     sprintf_s( (char*)&mydata.msg,256, "hi there :) " );
  39.    
  40.    
  41.     fout.write((char*) &mydata, sizeof(MyStruct));
  42. }
  43.  
  44. MyStruct* load()
  45. {
  46.     std::ifstream fin("struct.dat", std::ios::binary);
  47.     if(fin.bad())
  48.     {
  49.             fin.close();
  50.             return NULL;
  51.     }
  52.    
  53.     MyStruct *mydata = new MyStruct;
  54.    
  55.     fin.read((char*) mydata, sizeof(MyStruct));
  56.     return mydata;
  57. }
  58.  
  59. int main()
  60. {
  61.     cout << "[s]ave or [l]oad? " << endl;
  62.     char choice = ' ';
  63.     cin >> choice;
  64.     if (choice == 's')
  65.     {
  66.         save();
  67.     }else{
  68.         MyStruct *s;
  69.         s = load();
  70.        
  71.         // if loading the struct failed, its pointer will be NULL
  72.         if (s)
  73.         {
  74.             print_struct( s );
  75.             delete s;
  76.         }else{
  77.             cout << "failed to load struct" << endl;
  78.         }
  79.     }
  80.    
  81.    
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement