There is a binary file that stores 2 million 'Player' class object information.
I want to open the file in Visual Studio, read the information, and insert it into the members of the 'Player' class object in vector that I created.
This is the configuration of the Player class.
class Player {
std::string name;
int score;
int id;
size_t num; // Size of bytes obtained in the free store
char* p; // Start address of free memory
};
Binary files were saved by this way.
void Player::write( std::ostream& os ) {
os.write((char*)this, sizeof(Player));
os.write((char*)p, num);
}
I tried with this way. I used Release mode.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
class Player {
std::string name;
int score;
int id;
size_t num;
char* p;
public:
void printElements()
{
std::cout << "name:" << name << ", "
<< "id:" << id << ", "
<< "score:" << score << ", "
<< "num:" << num << std::endl;
}
};
int main() {
std::ifstream infile("file", std::ifstream::binary);
std::vector<Player> v;
v.reserve(2'000'000);
Player* player = new Player;
char* q = new char;
for (int i = 0; i < v.capacity(); i++) {
infile.read((char*)player, sizeof(Player));
infile.read((char*)q, sizeof(q));
v.push_back(*player);
v.at(i).printElements();
}
delete player;
delete q;
}
This is what I wanted.
name:jhxubuhgldh , id:476109 , score:435832437, num:969
name:pmemwohbgqwwg , id:789387 , score:257570203, num:481
name:zzirtu , id:1477302, score:172025616, num:37
name:nxkrhdujq , id:4481 , score:461657936, num:258
name:benijj , id:1867600, score:39352766, num:658
name:wvukciloi , id:734835 , score:416874932, num:605
name:fisp , id:1611284, score:194548462, num:734
name:xfjvbgocgnvgfr , id:995733 , score:181002072, num:834
name:rmg , id:911109 , score:153943559, num:415
...
However, I couldn't read more than one object's information with my code. I thought it was a problem caused by not being able to read the contents of char*p clearly, and I tried many things, but I couldn't find the answer myself.How can I read the binary file perfectly? Please let me know if there is anything lacking in the question.