程序存储的本质就是二进制。
因此,二进制文件读写,就是单纯的将内存中的二进制数据输出。
参考:https://blog.csdn.net/weixin_44190648/article/details/122358591
1.功能:将Student类对象st1、st2、st3写入data.txt。再把data.txt内容写入data1.txt,之后输出data1.txt内容。
代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string filename1 = "C:\\Users\\19a405\\Desktop\\data.txt";
string filename2 = "C:\\Users\\19a405\\Desktop\\data1.txt";
class student {
friend ostream& operator<<(ostream& os, const student& st);//友元类
private:
int no;
string name;
public:
student(const int no=0, const string& name="") :no(no), name(name) {}
};
ostream& operator<<(ostream& os, const student& st) {//输出函数重载
os << st.no << '\t' << st.name ;
return os;
}
bool Write(const string& filename, const student& st1) {
//c_str(),把string转为char
ofstream of(filename.c_str(), ios_base::out | ios_base::app | ios_base::binary);//文件写入,二进制形式,追加
if (of.is_open() == false) {
cout << "文件" << filename << "打开失败!" << endl;
return false;
}
of.write((char*)&st1, sizeof(student));//写入
of.close();
return true;
}
bool Read(const string& filename) {
ifstream ifile(filename.c_str(), ios_base::in);
if (ifile.is_open() == false) {
cout << "文件" << filename << "打开失败!" << endl;
return false;
}
//读取全部内容
/*char ch;
while (ifile.get(ch))
cout << ch;*/
student st;
while(ifile.read((char*)&st, sizeof(student))) {
cout << "***********" << endl;
cout << st << endl;//输出重载
}
ifile.close();
return true;
}
bool Backup(const string& filename1, const string& filename2) {
ifstream ifile(filename1, ios_base::binary | ios_base::in);
if (ifile.is_open() == false) {
cout << "文件" << filename1 << "打开失败!" << endl;
return false;
}
ofstream of(filename2, ios_base::binary | ios_base::out | ios_base::app);
if (of.is_open() == false) {
cout << "文件" << filename2 << "打开失败!" << endl;
}
student st;
while(ifile.read((char*)&st, sizeof(student))) {
of.write((char*)&st, sizeof(student));
}
ifile.close();
of.close();
return true;
}
int main()
{
student st1(123, "abc"), st2(456,"def"),st3(789,"ghl");
Write(filename1, st1) ;
Write(filename1, st2) ;
Write(filename1, st3);
Backup(filename1, filename2) ;
Read(filename2);
}
结果:
2.功能:将source.txt文件内容,读入Person类对象p3、p4中。
//将txt内容写入p3、p4
Person p3, p4;
ifstream ism1(source, ios::in | ios::binary);
ism1.read((char*)&p3, sizeof(Person));
ism1.read((char*)&p4, sizeof(Person));
ism1.close();
p3.Show();
p4.Show();
结果: