#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<fstream>
#include<string>
#include<cstring>
using namespace std;
class News{
public:
News ()
{number=0;name=string("unkonw");score1=0;score2=0;}
News(int value1,string value2,double value3,double value4);
int getnumber()
{ return number;}
double getscore1()
{ return score1;}
double getscore2()
{ return score2;}
string name;
int read_data(char* pbuff,int nlen)
{
//從pbuff讀資料
//number,score1,score2,長度,字串
number = *(int*)pbuff;
score1 = *(double*)(pbuff+sizeof(int));
score2 = *(double*)(pbuff+sizeof(int)+sizeof(double));
int nsize = *(int*)(pbuff+sizeof(int)+sizeof(double)+sizeof(double));
if (nsize>0&&nsize<50)//假設名字位元組數(0--50之間)
{
char *pname = (pbuff+sizeof(int)+sizeof(double)+sizeof(double)+sizeof(int));
name.assign(pname,nsize);
}
else
{
cout<<"名字長度讀取失敗"<<endl;
}
return sizeof(int)+sizeof(double)+sizeof(double)+sizeof(int)+nsize;
}
int write_data(char* pbuff,int nlen)
{
//向pbuff裡面寫資料
*(int*)pbuff = number;
*(double*)(pbuff+sizeof(int)) = score1;
*(double*)(pbuff+sizeof(int)+sizeof(double)) = score2;
int nsize = name.size();
*(int*)(pbuff+sizeof(int)+sizeof(double)+sizeof(double)) = nsize;
char *pname = (pbuff+sizeof(int)+sizeof(double)+sizeof(double)+sizeof(int));
memcpy(pname,name.c_str(),nsize);
return sizeof(int)+sizeof(double)+sizeof(double)+sizeof(int)+nsize;
}
public:
int number;
double score1,score2;
};
News::News(int value1,string value2,double value3,double value4)
{
number=value1;
name=value2;
score1=value3;
score2=value4;
}
int main(){
News student[3]={
News(1217,"周瑤",86.0,90.0),
News(1212,"劉暢",89.0,88.0),
News(1213,"李毅",93.0,98.0)};
ofstream outf("text.txt"); //向檔案輸入資料
int i;
if(!outf)
{ cout<<"cannot open";
exit(1);
}
outf<<"學號"<<' '<<' ';
outf<<"姓名"<<' '<<' '<<' ';
outf<<"高數"<<' '<<' ';
outf<<"線代"<<"\r\n";
for( i=0;i<=2;i++){
outf<<student[i].getnumber()<<' '<<' ';
outf<<student[i].name<<' '<<' '<<' ';
outf<<student[i].getscore1()<<' '<<' '<<' ';
outf<<student[i].getscore2()<<"\r\n";
}
ofstream f_ou("text.dat",ios::binary); //以二進位方式向檔案輸入資料
if(!f_ou)
{ cout<<"cannot open";
exit(1);
}
for( i=0;i<=2;i++)
{
char pbuff[1024]={0};
int write_len = student[i].write_data(pbuff,1024);
f_ou.write(pbuff,write_len);
//fout.seekp(write_len,ios::cur);
}
f_ou.close();
ifstream f_in("text.dat",ios::binary); //將資料再次輸入記憶體
News stu[3];
for(i=0;i<=2;i++)
{
News cls;
f_in.read((char*)&cls.number,sizeof(int));
f_in.read((char*)&cls.score1,sizeof(double));
f_in.read((char*)&cls.score2,sizeof(double));
int size = 0;
f_in.read((char*)&size,sizeof(int));
char szbuff[50];
f_in.read(szbuff,size);
cls.name.assign(szbuff,size);
// int read_len = student[i].read_data(pbuff,1024);
//inf.read(reinterpret_cast<char *>(&stu[i]),sizeof(stu[i]));
cout<<cls.getscore1()<<'\t'<<cls.name<<endl;
}
f_in.close();
return 0;
}