// 第二十一章流 7二进制文件和文本文件 //1 以文本形式输出到文件 /* #include <iostream> #include <fstream> using namespace std; //定义一个结构体people const int num=20; struct people { char name[num]; double weight; int tall; int age; char sex; }; int main() { people pe={"李能",78.5,181,25,'f'}; ofstream fout("people.dat",ios::out|ios::app); //打开.dat,用out或app方法 fout<<pe.name<<" "<<pe.age<<" "<<pe.sex<<" "<<pe.tall<<" "<<pe.weight<<" "<<"\n"; fout.close(); ifstream fin("people.dat"); char ch[255]; fin.getline(ch,255-1,0); cout<<ch; fin.close(); return 0; } */ //2 以二进制形式输出到文件 //假如我们换成以二进制形式输出,那么我们可以将第16地和第17行换下面的语句 //ofstream fout("people.dat",ios::binary) //fout.write((char*)&pe, sizeof pe); /*#include <iostream> #include <fstream> using namespace std; //定义一个结构体people const int num=20; struct people { char name[num]; double weight; int tall; int age; char sex; }; int main() { people pe={"李能",78.5,181,25,'f'}; ofstream fout("people.txt",ios::binary); fout.write((char*)&pe,sizeof pe); fout.close(); people pe1={"张玲",78.5,181,26,'f'}; ifstream fin("people.txt",ios::binary); fin.read((char*)&pe1,sizeof pe1); //这里是读取 cout<<pe1.name<<" "<<pe1.age<<" "<<pe1.sex<<" "<<pe1.tall<<" "<<pe1.weight<<" "<<"\n"; //fin.close(); return 0; } */