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

书籍源码

开发平台:

Visual C++

  1. //【例9.11】使用随机访问对【例9.10】进行改造。将入口(main())程序中的文件改为
  2. //输入输出文件,写完后将文件定位指针拨回文件开始处。
  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(fstream&dist);     //文件流类作为形式参数必须是引用
  18. void Bdatafromfile(fstream&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&dist,inventory&iv){
  28. dist<<left<<setw(20)<<iv.Description<<setw(10)<<iv.No;
  29. dist<<right<<setw(10)<<iv.Quantity<<setw(10)<<iv.Cost<<setw(10)<<iv.Retail<<endl;
  30. return dist;
  31. }
  32. void inventory::Bdatatofile(fstream&dist){
  33. dist.write(Description.c_str(),20); //由string类的c_str()函数转为char*
  34. dist.write(No.c_str(),10);
  35. dist.write((char*)&Quantity,sizeof(int));
  36. dist.write((char*)&Cost,sizeof(double));
  37. dist.write((char*)&Retail,sizeof(double));
  38. }
  39. void inventory::Bdatafromfile(fstream&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. cout<<"对象car1:"<<endl;
  53. cout<<car1;
  54. cout<<"对象motor1:"<<endl;
  55. cout<<motor1;
  56. cout<<"对象car2:"<<endl;
  57. cout<<car2;
  58. cout<<"对象motor2:"<<endl;
  59. cout<<motor2;
  60. fstream datafile("d:\Ex9_11.data",ios::in|ios::out|ios::binary);            //打开输入输出文件
  61. if(!datafile){
  62. datafile.clear(0);
  63. datafile.open("d:\Ex9_11.data",ios::out); //建立输出文件
  64. datafile.close();
  65. datafile.open("d:\Ex9_11.data",ios::in|ios::out|ios::binary);          //改为输入输出文件
  66. }
  67. car1.Bdatatofile(datafile);                     //保存对象
  68. motor1.Bdatatofile(datafile);
  69. datafile.seekg(50,ios::beg);                    //先重写motor2
  70. motor2.Bdatafromfile(datafile);
  71. datafile.seekg(0,ios::beg);                     //后重写car2
  72. car2.Bdatafromfile(datafile);
  73. cout<<"对象car2:"<<endl;
  74. cout<<car2;
  75. cout<<"对象motor2:"<<endl;
  76. cout<<motor2;
  77. datafile.close();
  78. return 0;
  79. }