Ex9_10.cpp
上传用户:wuzhousb
上传日期:2022-07-12
资源大小:380k
文件大小:2k
源码类别:

书籍源码

开发平台:

Visual C++

  1. //【例9.10】创建二进制数据文件,以及数据文件的读取。这两项操作设计为成员函数。
  2. //为与【例9.9】对比,采用同名的类,并有同样的数据成员。
  3. #include<fstream>
  4. #include<iostream>
  5. #include<iomanip>
  6. #include<string>
  7. using namespace std;
  8. class inventory{
  9. string Description;
  10. string No;
  11. int Quantity;
  12. double Cost;
  13. double Retail;
  14. public:
  15. inventory(string="#",string="0",int =0,double =0,double =0);
  16. friend ostream &operator<<(ostream&,inventory&);
  17. void Bdatatofile(ofstream&dest);     //文件流类作为形式参数必须是引用
  18. void Bdatafromfile(ifstream&sour);
  19. };
  20. inventory::inventory(string des,string no,int quan,double cost,double ret){
  21. Description=des;
  22. No=no;
  23. Quantity=quan;
  24. Cost=cost;
  25. Retail=ret;
  26. }
  27. ostream &operator<<(ostream&dest,inventory&iv){
  28. dest<<left<<setw(20)<<iv.Description<<setw(10)<<iv.No;
  29. dest<<right<<setw(10)<<iv.Quantity<<setw(10)<<iv.Cost<<setw(10)<<iv.Retail<<endl;
  30. return dest;
  31. }
  32. void inventory::Bdatatofile(ofstream&dest){
  33. dest.write(Description.c_str(),20); //由string类的c_str()函数转为char*
  34. dest.write(No.c_str(),10);
  35. dest.write((char*)&Quantity,sizeof(int));
  36. dest.write((char*)&Cost,sizeof(double));
  37. dest.write((char*)&Retail,sizeof(double));
  38. }
  39. void inventory::Bdatafromfile(ifstream&sour){
  40. char k[20];
  41. sour.read(k,20);
  42. Description=k;
  43. sour.read(k,10);
  44. No=k;
  45. sour.read((char*)&Quantity,sizeof(int));
  46. sour.read((char*)&Cost,sizeof(double));
  47. sour.read((char*)&Retail,sizeof(double));
  48. }//由此可见读和写是完全对称的过程,次序决不能错
  49. int main(){
  50. inventory car1("夏利2000","805637928",156,80000,105000),car2;
  51. inventory motor1("金城125","93612575",302,10000,13000),motor2;
  52. ofstream ddatafile("d:\Ex9_10.data",ios::out|ios::binary);
  53. car1.Bdatatofile(ddatafile);
  54. motor1.Bdatatofile(ddatafile);
  55. cout<<"对象car1:"<<endl;
  56. cout<<car1;
  57. cout<<"对象motor1:"<<endl;
  58. cout<<motor1;
  59. cout<<"对象car2:"<<endl;
  60. cout<<car2;
  61. cout<<"对象motor2:"<<endl;
  62. cout<<motor2;
  63. ddatafile.close();
  64. ifstream sdatafile("d:\Ex9_10.data",ios::in|ios::binary);//重新打开文件,从头读取数据
  65. car2.Bdatafromfile(sdatafile);                         //从文件读取数据拷贝到对象car2
  66. if(sdatafile.eof()==0) cout<<"读文件成功"<<endl; 
  67. cout<<"对象car2:"<<endl;
  68. cout<<car2;
  69. motor2.Bdatafromfile(sdatafile);                 //继续从文件读取数据拷贝到对象motor2
  70. if(sdatafile.eof()==0) cout<<"读文件成功"<<endl;
  71. cout<<"对象motor2:"<<endl;
  72. cout<<motor2;
  73. sdatafile.close();
  74. return 0;
  75. }