欢迎光临
我们一直在努力

对一个二进制文件进行读写操作

class person
{
public:
char name[20];
char data[20];
};
person staff[] = { {"zhangsan","1991"},{"lisi","1990"},{"wangwu","2000" } };

int main()
{
ofstream outfile("person.txt", ios::out | ios::binary | ios::trunc);

if (!outfile)
{
cout << "文件打开失败" << endl;
exit(1);
}
int n = sizeof(staff) / sizeof(staff[0]);
for (int i = 0; i < n; i++)
{
outfile.write(reinterpret_cast<char*>(& staff[i]), sizeof(staff[i]));
}

if (outfile.good())
{
cout << "内容写入成功" << endl;
}
else
{
cout << "内容写入失败" << endl;
}

outfile.close();

ifstream infile("person.txt", ios::in | ios::binary);

if (!infile)
{
cout << "文件读打开失败" << endl;
exit(1);
}

person temp;

while (infile.read(reinterpret_cast<char*>(&temp), sizeof(temp)))
{
cout << "姓名:" << temp.name << " " << "出生:" << temp.data << " " << endl;
}
if (infile.eof())
{
cout << "文件正常读完成" << endl;
}
else if (infile.fail())
{
cout << "文件读异常" << endl;
}

infile.close();

return 0;
}

赞(0)
未经允许不得转载:171主机测评 » 对一个二进制文件进行读写操作
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址