东方耀AI技术分享
标题:
linux中将类的对象写入文件并读入后打印对象信息
[打印本页]
作者:
东方耀
时间:
2021-7-27 16:13
标题:
linux中将类的对象写入文件并读入后打印对象信息
linux中将类的对象写入文件并读入后打印对象信息
#include <iostream>
#include <fstream>
#include <string.h>
class Teacher
{
private:
int age;
char name[64];
public:
Teacher(int _age, char *_name);
void printInfo();
};
Teacher::Teacher(int _age, char *_name)
{
Teacher::age = _age;
strcpy(Teacher::name, _name);
}
void Teacher::printInfo(){
std::cout << "name=" << Teacher::name << ",age=" << Teacher::age << std::endl;
}
//linux中将类的对象写入文件并读入后打印对象信息
int main(){
std::cout << "文件读入与写" << std::endl;
Teacher t1(30, "t30");
Teacher t2(33, "jiang");
// t1.printInfo();
// t2.printInfo();
//写入对象 linux注意细节:文件名必须是绝对路径
char *filename = "/home/jiang/jjj_opencl_works/io.data";
std::ofstream fout(filename, std::ios::out);
fout.write((char*)&t1, sizeof(Teacher));
fout.write((char*)&t2, sizeof(Teacher));
fout.close();
//读入文件
std::ifstream fin(filename, std::ios::in);
Teacher temp(0, " ");
fin.read((char *)&temp, sizeof(Teacher));
temp.printInfo();
fin.read((char *)&temp, sizeof(Teacher));
temp.printInfo();
fin.close();
return 0;
}
复制代码
欢迎光临 东方耀AI技术分享 (http://ai111.vip/)
Powered by Discuz! X3.4