#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdexcept>
#include<algorithm>
#include<fstream>
#include<string>
class make {
public:
make(const char* name, int age) {
this->age = age;
std::strcpy(this->name, name);
}
make() {}
char name[64];
int age;
};
//写文件
void test01() {
make m1("123", 123);
make m2("456", 456);
std::ofstream ofs;
ofs.open("test.txt",std::ios::out | std::ios::trunc | std::ios::binary);
if (!ofs.is_open()) {
std::cout << "open fail\n";
}
//写
ofs.write((const char*)&m1, sizeof(make));
ofs.write((const char*)&m2, sizeof(make));
ofs.close();
}
//read file
void test02() {
std::ifstream ifs;
ifs.open("test.txt", std::ios::in | std::ios::binary);
if (!ifs.is_open()) {
std::cout << "打开失败\n";
}
//read file
make m1, m2;
ifs.read((char*)&m1, sizeof(make));
ifs.read((char*)&m2, sizeof(make));
std::cout << "name:" << m1.name << " age:" << m1.age << '\n';
std::cout << "name:" << m2.name << " age:" << m2.age << '\n';
ifs.close();
}
auto main()->int32_t{
test01();
test02();
return static_cast<int>(0);
}
标签:std,name,二进制,读写,ios,age,io,include,make
From: https://www.cnblogs.com/lambdaios/p/17966658