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

书籍源码

开发平台:

Visual C++

  1. //强调输入输出文件中文件定位指针只有一个,输入输出都是用此定位指针。
  2. #include<fstream>
  3. #include<iostream>
  4. #include<iomanip>
  5. #include<string>
  6. using namespace std;
  7. //本例说明只有一个文件定位指针
  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_1.data",ios::in|ios::out|ios::binary);
  61. if(!datafile){
  62. datafile.clear(0);
  63. datafile.open("d:\Ex9_11_1.data",ios::out); //建立输出文件
  64. datafile.close();
  65. datafile.open("d:\Ex9_11_1.data",ios::in|ios::out|ios::binary); //改为输入输出文件
  66. }
  67. car1.Bdatatofile(datafile);//存car1
  68. datafile.seekp(0,ios::beg);//重定位,用seekp()完全一样
  69. car2.Bdatafromfile(datafile);//重写car2
  70. cout<<"对象car2:"<<endl;
  71. cout<<car2;
  72. datafile.seekg(0,ios::end);//重定位,用seekg()完全一样
  73. motor1.Bdatatofile(datafile);//存motor1
  74. datafile.seekp(50,ios::beg);//重定位,用seekp()完全一样
  75. motor2.Bdatafromfile(datafile);//重写motor2
  76. cout<<"对象motor2:"<<endl;
  77. cout<<motor2;
  78. datafile.close();
  79. return 0;
  80. }