#include <iostream>
#include <fstream>
using namespace std;
struct staff
{
int num;
char name[20];
int age;
double pay;
};
int main()
{
staff staf[7]={1,"li",34,1203,2,"wang",23,1204,3,"fun",54,778,4,"xue",45,475,5,"ling",39,890},staf1;
fstream iofile("staff.dat",ios::in|ios::out|ios::binary);
if(!iofile)
{
cerr<<"open error!"<<endl;
abort();
}
int i,m,num;
cout<<"five staff:"<<endl;
for(i=0;i<5;i++)
{
cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;
iofile.write((char *)&staf[i],sizeof(staf[i]));
}
cout<<"please input data you want insert: "<<endl;
iofile.seekp(0,ios::end);
for(i=0;i<2;i++)
{
cin>>staf1.num>>staf1.name>>staf1.age>>staf1.pay;
iofile.write((char *)&staf1,sizeof(staf1));
}//每次输出的结果都是最初输入的两个值,以后不能再改变了!(由编译结果图看到,以后无论我输入最后两个员工数据是多少,他都是输出上面的那七个员工值,最后面的那两个员工数据是我首次输入的,以后变化不了了!);其次为什么写入staf1而不是staf呢?(iofile.write((char *)&staf1,sizeof(staf1));为什么不能写为iofile.write((char *)&staf,sizeof(staf));staf不是定义了staf[7]么,直接用staf写入后两个职工数据为什么不行!)
cout<<"seven staff: "<<endl;
iofile.seekg(0,ios::beg);
for(i=0;i<7;i++)
{
iofile.read((char*)&staf[i],sizeof(staf[i]));
cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;//最后的两个值不是写入staf1了么,为什么这里输出staf,却可以输出staf1中的两个员工信息呢?(搞不清楚什么时候用iofile.read((char*)&staf[i],sizeof(staf[i]));什么时候用iofile.read((char*)&staf1[i],sizeof(staf1[i]));)
}
bool find;
cout<<"enter number you want search ,enter 0 to stop.";
cin>>num;
while(num)
{
find=false;
iofile.seekg(0,ios::beg);
for(i=0;i<7;i++)
{
iofile.read((char*)&staf[i],sizeof(staf[i]));
if(num==staf[i].num)
{
m=iofile.tellg();
cout<<num<<" is No."<<m/sizeof(staf1)<<endl;//请高手帮忙解释一下m/sizeof(staf1)是什么意思啊?我知道m是什么意思!/后面添加的东西觉得不理解!
cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;
find=true;
break;
}
}
if(!find)
cout<<"can't find "<<num<<endl;
cout<<"enter number you want search ,enter 0 to stop.";
cin>>num;
}
iofile.close();
return 0;
}
输出结果是:
Five staff:
1 li 34 1203
2wang 23 1204
3 fun 54 778
4 xue 45 475
5 ling 39 890
Plesase input data you want insert:
6 wng 56 789
7 nge 45 890
Seven staff::
1 li 34 1203
2wang 23 1204
3 fun 54 778
4 xue 45 475
5 ling 39 890
5 mei 56 890
7 sang 45 980
最初我输入后两个员工数据是:5 mei 56 890 ; 7 sang 45 980(后来我无论输入什么值,比如6 wng 56 789 ;7 nge 45 890最后才出现的结果都是首次输入的:5 mei 56 890 ; 7 sang 45 980)为什么?请高手解答啊!!!