东方耀AI技术分享

标题: linux中将类的对象写入文件并读入后打印对象信息 [打印本页]

作者: 东方耀    时间: 2021-7-27 16:13
标题: linux中将类的对象写入文件并读入后打印对象信息





linux中将类的对象写入文件并读入后打印对象信息

  1. #include <iostream>
  2. #include <fstream>
  3. #include <string.h>

  4. class Teacher
  5. {
  6. private:
  7.     int age;
  8.     char name[64];
  9. public:
  10.     Teacher(int _age, char *_name);
  11.     void printInfo();
  12. };

  13. Teacher::Teacher(int _age, char *_name)
  14. {
  15.     Teacher::age = _age;
  16.     strcpy(Teacher::name, _name);
  17. }

  18. void Teacher::printInfo(){
  19.     std::cout << "name=" << Teacher::name << ",age=" << Teacher::age << std::endl;
  20. }

  21. //linux中将类的对象写入文件并读入后打印对象信息
  22. int main(){
  23.     std::cout << "文件读入与写" << std::endl;
  24.     Teacher t1(30, "t30");
  25.     Teacher t2(33, "jiang");

  26.     // t1.printInfo();
  27.     // t2.printInfo();

  28.     //写入对象  linux注意细节:文件名必须是绝对路径
  29.     char *filename = "/home/jiang/jjj_opencl_works/io.data";
  30.     std::ofstream fout(filename, std::ios::out);
  31.     fout.write((char*)&t1, sizeof(Teacher));
  32.     fout.write((char*)&t2, sizeof(Teacher));
  33.     fout.close();

  34.     //读入文件
  35.     std::ifstream fin(filename, std::ios::in);
  36.     Teacher temp(0, " ");
  37.     fin.read((char *)&temp, sizeof(Teacher));
  38.     temp.printInfo();
  39.     fin.read((char *)&temp, sizeof(Teacher));
  40.     temp.printInfo();
  41.     fin.close();


  42.     return 0;
  43. }



复制代码







欢迎光临 东方耀AI技术分享 (http://ai111.vip/) Powered by Discuz! X3.4