Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <string>
- #include <iostream>
- #include <stdlib.h>
- using namespace std;
- struct MyStruct
- {
- float a,b,c;
- int d;
- char msg[256];
- };
- void print_struct( MyStruct *s )
- {
- std::cout << "a,b,c :" << s->a << ", " << s->b << ", " << s->c << endl;
- std::cout << "d :" << s->d << endl;
- std::cout << "msg :" << s->msg << endl;
- }
- void save()
- {
- std::ofstream fout("struct.dat", std::ios::binary);
- if(fout.bad())
- {
- fout.close();
- return;
- }
- MyStruct mydata;
- mydata.a = 3.14159;
- mydata.b = 6.28;
- mydata.c = 2.73;
- mydata.d = 42;
- // Format a string...
- sprintf_s( (char*)&mydata.msg,256, "hi there :) " );
- fout.write((char*) &mydata, sizeof(MyStruct));
- }
- MyStruct* load()
- {
- std::ifstream fin("struct.dat", std::ios::binary);
- if(fin.bad())
- {
- fin.close();
- return NULL;
- }
- MyStruct *mydata = new MyStruct;
- fin.read((char*) mydata, sizeof(MyStruct));
- return mydata;
- }
- int main()
- {
- cout << "[s]ave or [l]oad? " << endl;
- char choice = ' ';
- cin >> choice;
- if (choice == 's')
- {
- save();
- }else{
- MyStruct *s;
- s = load();
- // if loading the struct failed, its pointer will be NULL
- if (s)
- {
- print_struct( s );
- delete s;
- }else{
- cout << "failed to load struct" << endl;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement