I want to be able to write a linked list of type Music into a binary file, then later, read it back into a linked list. Of course, I'm having problems doing so. From what I understand, my problem is that string is a variable length. Since a string isn't always the same size, when reading it, there's no telling how much to read. I was going to convert my class to fixed-length cstrings to fix the problem. Actually, I tried to, but had a few other problems that were caused by that. My question is, is there any way to do achieve what I want without drastically altering my code?
void ReadBinFile(Node * head, string filename)
{
Music new_song;
ifstream bin(filename, ios::in | ios::binary);
if (bin.is_open())
{
while (!bin.eof())
{
bin.read(reinterpret_cast<char *>(&new_song), sizeof(Music));
if (!bin.eof())
{
Node * new_node = CreateNode(new_song);
AppendNode(head, new_node);
}
}
bin.close();
}
}
void Save(Node * head, string filename)
{
ofstream bin(filename, ios::out | ios::binary);
if (bin.is_open())
{
Node * traveler = head;
while (traveler != nullptr)
{
bin.write(reinterpret_cast<char *>(&(traveler->song)), sizeof(Music));
traveler = traveler->next;
}
bin.close();
}
}
Node * CreateNode(Music song)
{
Node * new_node = new Node;
new_node->song = song;
new_node->next = nullptr;
return new_node;
}
//music.h
class Music
{
public:
Music(string name = "", string artist = "");
private:
string m_name;
string m_artist;
};