I am fairly new to c++. I am using the Visual Studio IDE. I am learning how to send objects to files and how to retreive them. While retrieving so i get an Exception at that place. I don't know what to do
#include <iostream>
#include <fstream>
class Entity
{
public:
int ID;
const char* name;
Entity(): ID(-1), name("NOT ASSIGNED") {}
Entity(int a, const char* b) : ID(a), name(b) {}
};
std::ostream& operator<<(std::ostream& stream, Entity &e)
{
stream << e.ID << " " << e.name << std::endl; //exception is thrown here
return stream;
}
void WriteToFile(Entity e)
{
std::cout << "Writing to file\n";
std::ofstream fout("ENTITY.txt", std::ios::app|std::ios::binary);
fout.write((char*)&e, sizeof(e));
fout.close();
}
void ReadFromFile()
{
std::ifstream fin("ENTITY.txt", std::ios::binary | std::ios::in);
while (!fin.eof())
{
Entity a;
fin.read((char*)&a, sizeof(a));
std::cout << a;
}
}
int main()
{
Entity a(1, "A");
Entity b(15, "C");
Entity x;
WriteToFile(a);
WriteToFile(b);
WriteToFile(x);
ReadFromFile();
}
I don't know where you are learning from but it isn't very good if it doesn't tell you that istream::read
and ostream::write
cannot be used for objects such as Entity
.
In order to work with read
and write
an object must be a POD type, POD stands for plain old data. Additionally anything with a pointer isn't going to work (because write
will write the pointer itself, not what the pointer is pointing at, and the pointer value is unlikely to be valid when read again by read
).
What you are trying to do is called serialization, and it's more complex in C++ than in some other languages. Because of this you should probably look at a serialization library. For instance boost serialization
User contributions licensed under CC BY-SA 3.0