Hello! I was trying to create a file where object data could be written, so that different programs could use it. I'm having trouble understanding just exactly what goes on when a program writes to a file, so I hope somebody could help me out.
First, this program saves an object of the class "Something" to a file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <fstream>
#include <iostream>
using namespace std;
class something {
public:
int weight;
int size;
}thing1;
int main()
{
thing1.size = 1;
ifstream::pos_type size = sizeof(thing1);
Something * memblock;
memblock = &thing1;
ofstream save1;
save1.open("saved", ios::binary);
save1.seekp(0,ios::beg);
save1.write((char*)&memblock,size);
save1.close();
return 0;
}
| |
First, I assume I must use a binary file to store this kind of data. Then, since the write method only takes char pointers as its first arguement, I typecasted my object pointer as a char*. As I understand it, this tells the program to take the values stored in the memory address of thing1, and writes it to a file called "saved.
The second program has the same "Something" class, and it's supposed to read from the "saved" file to assign its values to a new object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <iostream>
#include <fstream>
using namespace std;
class Something {
public:
int weight;
int size;
};
int main()
{
ifstream file;
file.open("saved",ios::binary);
int beginning,end;
beginning = file.tellg();
file.seekg(0, ios::end);
end = file.tellg();
ifstream::pos_type size = (fin - inicio);
Something * memblock = new Something;
Something thing2;
file.seekg(0,ios::beg);
file.read((char*)&memblock,size);
file.close();
cout << &memblock << endl;
thing2 = *memblock;
cout << thing2.size << endl;
return 0;
}
| |
Both programs compile and run, but in the end, when I try to get the size value of thing2, the output is "0", when it should be "1".
I'm pretty surprised that it actually compiled, since I'm not really sure what is going on.