(4)为验证输出文件正确,再将binary_score.dat中的记录逐一读出到学生对象中并输出查看。
代码
#include<iostream> #include<fstream> #include<cstdlib> #include<cstring> using namespace std; class Student { public: Student(){}; friend ostream &operator<<(ostream &out,Student &s); friend istream &operator>>(istream &in,Student &s); private: int number; string name; double cpp,math,english; }; ostream &operator<<(ostream &out,Student &s) { out<<s.number<<"\t"<<s.name<<"\t"<<s.cpp<<"\t"<<s.math<<"\t"<<s.english; return out; } istream &operator>>(istream &in,Student &s) { in>>s.number>>s.name>>s.cpp>>s.math>>s.english; return in; } int main() { ifstream infile; infile.open("score.dat",ios::in); if(!infile) { cout<<"open,error!"; exit(1); } Student s[101]; int i=0; while(!infile.eof()) { infile>>s[i]; i++; } infile.close(); ofstream outfile("binary_score.dat",ios::out|ios::binary); if(!outfile) { cout<<"open,error!"; exit(1); } for(i=0;i<100;i++) { outfile.write((char*)&s[i], sizeof(s[i])); } cin>>s[i]; outfile.close(); fstream infile2("binary_score.dat",ios::out|ios::binary); Student a; while(!infile2.eof()) { infile2.read((char*)&a, sizeof(a)); if(infile2.eof()) break; cout<<a; } infile2.close(); return 0; }
原文:http://blog.csdn.net/blue_skyrim/article/details/46552287