#include<stdlib.h>
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
/*
5.2.1 写二进制文件
二进制方式写文件主要利用流对象调用成员函数write
函数原型 :ostream & write(const char * buffer, int len);
参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数
*/
class Person{
public:
char name[64]; // 用string向二进制文件写入时容易出错
int age;
};
void test1(){
ofstream ofs;
ofs.open("person.txt", ios::out|ios::binary);
// 上述两行可以合并为:ofstream ofs.open("person.txt", ios::out|ios::binary);
Person p = {"张三", 19};
ofs.write((const char *)&p, sizeof(Person));
ofs.close();
// 写入的文件,直接打开可能会有乱码,正常,因为二进制,能够用程序读取回来就ok
}
int main()
{
test1();
system("pause");
return 0;
}
12.2.1重学C++之【写二进制文件】
猜你喜欢
转载自blog.csdn.net/HAIFEI666/article/details/114981227
今日推荐
周排行