【发布时间】:2021-04-18 06:25:31
【问题描述】:
由于我不擅长英语,我提前为我缺乏解释表示歉意。 我创建了一个存储这些对象的二进制文件。我想阅读它并推回矢量,但我不知道该怎么做。
class Player
{
string name;
int score;
int id;
size_t num;
char* p;
};
这些函数在写入二进制文件时使用。
void write(ostream& os)
{
os.write((char*)this, sizeof(Player));
os.write((char*)p, num);
}
这是类的运算符重载函数。 下面是main函数,就是这样写的,用来读取文件的,但是效果不好。
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), {});
}
我应该怎么做才能读取文件? 我想读取每个对象的数据,但我认为正在读取的数据比我想要的要多。
#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();
}
【问题讨论】:
-
工作不差表示工作正常。可能你的意思是别的。作为一般建议,您可能只想使用
std::copy。 -
顺便说一下,您的代码不可编译也不可运行。请提供minimal reproducible example。
-
你的最后一个例子甚至没有编译。请调整一下。
标签: c++ fstream stdvector ifstream