#include<iostream>
#include<string>
#include<fstream>//文件流工具类头文件
using namespace std;
class Person {
public:
int a;
char str[64];
};
void test1() {
//1,包含头文件fstream
//2,创建文件流对象
ofstream ofs("wxd.txt", ios::out | ios::binary|ios::trunc);
//3,打开文件流对象
//4,写数据 “<<”
Person p = { 18,"王五" };
cout << p.a << " " << p.str << endl;
ofs.write((const char*)&p, sizeof(Person));
//5,关闭文件流对像
ofs.close();
}
void test() {
//1,包含头文件fstream
//2,创建文件流对象
ifstream ifs("wxd.txt", ios::in | ios::binary);
//3,打开文件流对象
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return;
}
//4,写数据 “<<”
Person p;
ifs.read((char*)&p, sizeof(Person));
cout << p.a << " " << p.str << endl;
//5,关闭文件流对像
ifs.close();
}
int main() {
test();
return 0;
}
c++二进制文件的读写
最新推荐文章于 2024-03-05 08:43:27 发布