C++中输入输出流及文件流操作总结

2020-01-06 15:51:54于海丽

二进制文件操作

    对二进制文件的读写主要用istream类的成员函数read和write来实现。这两个成员函数的原型为

     istream& read(char *buffer,int len);

     ostream& write(const char * buffer,int len);

 


#include <iostream>
using namespace std;
#include <fstream>

class Teacher
{
public:
 Teacher()
 {

 }
 Teacher(int age,char name[20])
 {
 this->age = age;
 strcpy(this->name,name);
 }
 void prinfInfo()
 {
 cout<<"Teacher name:"<<this->name<<"  age:"<<this->age<<endl;
 }
private:
 int age;
 char name[20];
};

int main()
{
 Teacher t1(31,"xiaoming");
 Teacher t2(32,"xiaohong");
 Teacher t3(33,"xiaohua");
 Teacher t4(34,"xiaoxin");
 char fname[] = "d:/file2";
 fstream fs(fname,ios::binary|ios::out);
 if(!fs)
 {
 cout<<"文件打开失败"<<endl;
 }
 fs.write((char *)&t1,sizeof(Teacher));
 fs.write((char *)&t2,sizeof(Teacher));
 fs.write((char *)&t3,sizeof(Teacher));
 fs.write((char *)&t4,sizeof(Teacher));
 fs.flush();
 fs.close();

 fstream fs2(fname,ios::binary|ios::in);
 if(!fs)
 {
 cout<<"文件打开失败"<<endl;
 }
 Teacher tt;
 fs2.read((char *)&tt,sizeof(Teacher));
 tt.prinfInfo();
 fs2.read((char *)&tt,sizeof(Teacher));
 tt.prinfInfo();
 fs2.read((char *)&tt,sizeof(Teacher));
 tt.prinfInfo();
 fs2.read((char *)&tt,sizeof(Teacher));
 tt.prinfInfo();
 fs2.close();

 system("pause");
 return 0;
}

输出:


Teacher name:xiaoming  age:31
Teacher name:xiaohong  age:32
Teacher name:xiaohua  age:33
Teacher name:xiaoxin  age:34

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。


注:相关教程知识阅读请移步到C++教程频道。