I apologize in advance for my lack of explanation because I am not good at English. I created a binary file that stores these objects. I want to read it and push back on the vector, but I don't know what to do.
class Player
{
string name;
int score;
int id;
size_t num;
char* p;
};
These functions were used when writing to binary files.
void write(ostream& os)
{
os.write((char*)this, sizeof(Player));
os.write((char*)p, num);
}
This is the operator overload function of the class. Below it is the main function, which is written in this way to read the file, but is not working poorly.
istream& operator>> (istream& is, Player& p)
{
getline(is, p.name, '\0');
is.read((char*)&p.score, sizeof(int));
is.read((char*)&p.id, sizeof(int));
is.read((char*)&p.num, sizeof(size_t));
return is;
}
int main()
{
ifstream in{ "Myfile", ios::binary };
vector<Player> players(istream_iterator<Player>(in), {});
}
What should I do to read the file? I want to read the data of each object, but I think more data is being read than I want.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
class Player
{
string name;
int score;
int id;
size_t num;
char* p;
public:
Player(): name{NULL}, score{0}, id{0}, num{0}, p{nullptr}
{}
Player(string name, int score, int id, size_t num) :
name{ name }, score{ score }, id{ id }, num{ num }, p{ new char[num] }
{}
~Player()
{
delete[] p;
}
/*Player(const Player& other) : name{ other.name }, score{ other.score }, id{ other.id }, num{ other.num }, p{ new char[num] }
{
memcpy(p, other.p, num);
}*/
void write(ostream& os) {
os.write((char*)this, sizeof(Player));
os.write((char*)p, num);
}
friend istream& operator>> (istream& is, Player& p);
};
istream& operator>> (istream& is, Player& p)
{
getline(is, p.name, '\0');
is.read((char*)&p.score, sizeof(int));
is.read((char*)&p.id, sizeof(int));
is.read((char*)&p.num, sizeof(size_t));
return is;
}
int main()
{
ifstream in{ "Myfile", ios::binary };
vector<Player> players(istream_iterator<Player>(in), {});
in.close();
}