读书人

二进制文件的随机访问,该如何解决

发布时间: 2012-08-28 12:37:01 作者: rapoo

二进制文件的随机访问
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


class Student
{
public:
Student ();
Student (int num, string nam, float s)
{
number = num;
name = nam;
score = s;
}
void display ();
//private:
int number;
string name;
float score;
};

void Student::display ()
{
cout <<number << endl;
cout << name << endl;
cout << score << endl;
cout << endl << endl;
}

int main ()
{
Student stu[5] = {Student(1, "yang", 100), Student(2, "xiao", 99), Student(3, "ying", 98), Student (4, "liu", 521), Student (5, "na", 5210)};
fstream iofile ("file1",ios::in|ios::out|ios::binary);
if (!iofile)
{
cerr << "open file error " << endl;
exit (1);
}
for (int i = 0; i < 5; i++)
{
iofile.write ((char*)&stu[i], sizeof (stu[i]));
stu[i].display ();
}
Student stu1[3];
for ( i = 0; i < 5; i += 2)
{
iofile.seekg (i * sizeof (stu[i]),ios::beg);
iofile.read ((char *)&stu1[i/2], sizeof (stu1[i/2]));
cout << stu1[i/2].number << endl;
cout << stu1[i/2].name << endl;
cout << stu1[i/2].score << endl;
}
stu[2].number = 801060127;
stu[2].name = "yang xiaoying";
stu[2].score = 250;
iofile.seekp (2 * sizeof (stu[0]), ios::beg);
iofile.write ((char *)&stu[2], sizeof (stu[2]));
iofile.seekp (5 * sizeof (stu[0]), ios::beg);
for (i = 0; i < 5; i++)
{
cout << stu[i].number << endl;
cout << stu[i].name << endl;
cout << stu[i].score << endl;
}
cout << endl;
return 0;
}

编译没错!连接出错!!晕死了。。。各位大侠帮帮忙把....


[解决办法]
Student ();
===================
这个构造函数没定义
[解决办法]
for ( i = 0; i < 5; i += 2) //应该是int i=0;
for (i = 0; i < 5; i++)//应该是int i=0;
Student (){}; 记得定义

读书人网 >C++

热点推荐