我需要编写一个类到二进制文件中,然后需要读取它。
我有Triangle和BinaryFile类,以及其他一些类。我不确定我是在错误地写入还是错误地读取。读取时发生错误。调试后,我认为对于我的私有变量,它获取了不适当的数据。如果有人能给我一些关于如何使其正常工作的建议,我将非常高兴。
我不确定是否应该粘贴整个代码,因此我将为您提供一小段代码片段。 以防万一,这是我的源代码的下载链接:
我有Triangle和BinaryFile类,以及其他一些类。我不确定我是在错误地写入还是错误地读取。读取时发生错误。调试后,我认为对于我的私有变量,它获取了不适当的数据。如果有人能给我一些关于如何使其正常工作的建议,我将非常高兴。
我不确定是否应该粘贴整个代码,因此我将为您提供一小段代码片段。 以防万一,这是我的源代码的下载链接:
https://my.pcloud.com/publink/show?code=XZJ7CYZbsLWLglqV5p83csijcEUTFqqpM3k
我是一个编程新手,我的英语不太好,所以提前为我的错误道歉。
class Point
{
private:
int x;
int y;
};
class Figure
{
private:
string name;
string type;
};
class Triangle: public Figure
{
private:
Point p1, p2, p3;
};
class BinaryFile
{
private:
string FileName;
fstream File;
public:
//...
void AddNewFigure(istream& stream)
{
File.open(this->FileName, ios::binary | ios::app);
if(!this->File)
{
cerr<<"File error <"<<this->FileName<<">\n";
exit(1);
}
Triangle fig;
fig.MakeNewFigure(stream);
File.write((char*)&fig, sizeof(Triangle));
File.close();
}
Triangle GetTriangle()
{
Triangle trig;
Point p;
string str(""); int x(0);
File.open(this->FileName, ios::binary | ios::in);
if(!this->File)
{
cerr<<"File error <"<<this->FileName<<">\n";
exit(1);
}
File.read((char*)&trig, sizeof(Triangle));
File.close();
return trig;
}
};