C++文件操作——二进制读写文件

二进制的方式进行读写操作

ios::binary

#include<iostream>
#include<fstream>
using namespace std;
二进制文件,写文件
class person{
public:
char m_Name[64];
int m_age;
}
void test(){
1.包含头文件
2.创建新文件
ofstream ofs;
3.打开文件
ofs.open("person.txt",ios::out|ios::binary);
person p={"关羽",23};
4.写文件
ofs.write(const char *)&p,sizeof(person);

5.关闭
ofs.close();
}

=============================================
二进制方式
读文件

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

class person{
public:

string m_Name[64];
int m_age;
}

void test(){
ifstream ifs;

ifs.open("person.txt",ios::in|ios::binary);
if(!ifs.is_open()){
cout<<"没有此文件"<<endl;
return ;
}
person p;

ifs.read((char *)&p,sizeof(p));
cout <<"p.name=" <<p.name <<","<<"p.age="<< p.age << endl;
ifs.close();
}

posted @ 2021-02-04 22:50  云小道  阅读(407)  评论(0编辑  收藏  举报