i want able write linked list of type music binary file, later, read linked list. of course, i'm having problems doing so. understand, problem string variable length. since string isn't same size, when reading it, there's no telling how read. going convert class fixed-length cstrings fix problem. actually, tried to, had few other problems caused that. question is, there way achieve want without drastically altering 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; };
unfortunately use strings, classes on own (with dynamically assigned length). if want write whole class, it'd have all-constant-size, wouldn't recommend it.
add read , write methods class , read/write each field on it's own.
clarification:
you want change music that:
class music { public: music(string name = "", string artist = ""); void write(std::string filename); void read(str::string filename); private: string m_name; string m_artist; };
can open file in binary mode , write name, write artist:
size_t len = str.size();
write length of string
file.write(reinterpret_cast<const char*>(&len), sizeof(len));
write actual string data:
file.write(str.c_str(), len);
, read same way -> read size first, read many chars ;)
restructure code little bit, think it'd right way this.
Comments
Post a Comment