上夜班研究,勿回复,谢谢.
程序代码:
#include <iostream> #include <fstream> #include<iomanip> using namespace std; const int n=20; const char* file="like.txt"; struct girl { char name[n]; int age; double beautiful; double tall; char sex[5]; }; void main() { bool q=false; char x; long count=0; girl a={"林云飞",21,999.999,1.63f,"女"}; girl b={"苍井空",28,60,1.619f,"女"}; ofstream fcout(file,ios::binary); fcout.write((char*)&a,sizeof a); fcout.close(); fcout.open(file,ios::in|ios::out|ios::binary); if(fcout.is_open()) { fcout.seekp(sizeof a,ios::beg); fcout.write((char*)&b,sizeof b); fcout.close(); } else { cout<<"打开失败!"<<endl; exit(EXIT_FAILURE); } ifstream fcin(file,ios::binary); if(fcin.is_open()) { fcin.seekg(0); cout<<fixed; while(fcin.read((char*)&a,sizeof a)) { cout<<count++<<":"<<setw(10)<<a.name<<setw(10)<<a.age<<setw(10)<<a.sex<<setw(10)<<setprecision(2)<<a.tall<<setw(10)<<setprecision(4)<<a.beautiful<<endl; } if(fcin.eof()) { fcin.clear(); //fcin.close(); } else { cout<<"读取失败!"<<endl; exit(EXIT_FAILURE); } } else { cout<<"打开失败!"<<endl; exit(EXIT_FAILURE); } while(1) { cout<<"请输入你希望改编的编号"<<endl; long line; cin>>line; if(line<0||line>=count) { cout<<"输入错误!"<<endl; exit(EXIT_FAILURE); } streampos place=line*sizeof a; //fcin.open(file,ios::in|ios::out|ios::binary); fcin.seekg(place); if(fcin.fail()) { cout<<"读入失败"<<endl; exit(EXIT_FAILURE); } else { fcin.read((char*)&a,sizeof a); cout<<line<<":"<<setw(10)<<a.name<<setw(10)<<a.age<<setw(10)<<a.sex<<setw(10)<<setprecision(2)<<a.tall<<setw(10)<<setprecision(4)<<a.beautiful<<endl; fcin.clear(); fcin.close(); } cout<<"请输入更改的姓名: "; cin>>a.name; cout<<"请输入更改的年龄; "; cin>>a.age; cout<<"请输入更改的性别; "; cin>>a.sex; cout<<"请输入更改的身高; "; cin>>a.tall; cout<<"请输入更改的美丽程度; "; cin>>a.beautiful; cout<<"是否继续输入?是:y 否: n"<<endl; cin>>x; if(x=='n') { fcout.open(file,ios::in|ios::binary); fcout.seekp(place); if(fcout.fail()) { cout<<"读取失败"<<endl; exit(EXIT_FAILURE); } else { fcout.write((char*)&a,sizeof a); fcout.close(); } q=true; } else if(x=='y') { fcout.open(file,ios::in|ios::binary); fcout.seekp(place); if(fcout.fail()) { cout<<"读取失败"<<endl; exit(EXIT_FAILURE); } else { fcout.write((char*)&a,sizeof a); fcout.close(); } continue; } else { cout<<"请输入小写y或者n"<<endl; } if(q) break; } fcin.open(file,ios::binary); fcin.seekg(0); count=0; while(fcin.read((char*)&a,sizeof a)) { cout<<count++<<":"<<setw(10)<<a.name<<setw(10)<<a.age<<setw(10)<<a.sex<<setw(10)<<setprecision(2)<<a.tall<<setw(10)<<setprecision(4)<<a.beautiful<<endl; } fcin.clear(); fcin.close(); }