C++的二进制文件

C++的二进制文件读写

ios::app|ios::binary表示打开二进制文件进行追加

预处理文件

和类的新建

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

class student 
{
public:
    int Num;
    char Name[10];
    int Cla;
    char Sex;
    int Age;
    float Chiness,Math,English;
    char Info[40];
    void init(student *stu,int n);
    void write();
    void display();
};

类中方法的定义--写

void student::init(student *stu,int n)
{
    cout<<"--init student --"<<endl;
    ofstream fout("f1.dat",ios::binary);
    for(int i=0;i<n;i++)
    {
        fout.write((char*)(&stu[i]),sizeof(student));

    }fout.close();
}
void student::write()
{
    cout<<"--从键盘中输入学生信息,然后追加到二进制文件中--"<<endl;
    ofstream fout("f1.dat",ios::app|ios::binary);
    cout<<"input data :"<<endl;
    cin>>Num;
    cin>>Name;
    cin>>Cla;
    cin>>Sex;
    cin>>Age;
    cin>>Chiness;
    cin>>Math;
    cin>>English;
    cin>>Info;
    fout.write((char*)(this),sizeof(*this));    //类是应用引用类型
    fout.close();

}

类中方法的定义--读

void student::display()
{
    student stu;
    cout<<"dispaly  "<<endl;
    ifstream fin("f1.dat",ios::binary);
    fin.read((char*)(&stu),sizeof(student));        //读出二进制文件的第一个学生数据
    while(!fin.eof())
    {
        cout<<stu.Num<<endl;                            //元友类操作符 << 的应用
    fin.read((char*)(&stu),sizeof(student));        //读出二进制文件的第一个学生数据
    }

    fin.close();
}

类中方法的定义--查找

int search1(int num1)
{
        student stu;
    cout<<"search the num of student "<<endl;
    ifstream fin("f1.dat",ios::binary);
    fin.read((char*)(&stu),sizeof(student));
    while(!fin.eof())
    {
        if(stu.Num==num1)
            //search successfully
        {
            cout<<stu.Num<<" "<<stu.Name<<endl;
            fin.close();
            return 1;
        }
            fin.read((char*)(&stu),sizeof(student));
    }
    fin.close();
    cout<<"fail "<<endl;
    return 0;

}

主函数的启用

int main ()
{
    const int n=3;
    student stu[n]=
    {
        {6007701,"liyi",6,'m',16,88,99,89,"a good student"},
        {6007702,"wanger",6,'m',16,88,99,89,"a good student"},
        {6007703,"zhangsan",6,'m',16,88,99,89,"a good student"}
    };
    student ss;
    ss.init(stu,n);
    ss.display();
    ss.write();
    ss.display();
    search1(6007701);
    return 0;

}

 

posted @ 2019-03-20 17:43  lincoding`  阅读(767)  评论(0编辑  收藏  举报