对输入输出二进制文件流的操作

#include 
#include 
#include 

using namespace std;

struct staff
{
    int num;
    char name[20];
    int age;
    double pay;
};

int main()
{
    staff staf[7]={2101,"Li",34,1203,2104,"Wang",23,675.5,2108,"Fun",54,788,3006,"Xue",45,
    476.5,5101,"Ling",39,656.6},staf1;
    ofstream ofile("staff.dat",ios::out|ios::binary);   //建立输出文件流
    //fstream io_file ("staff_io.dat",ios::out|ios::in|ios::binary);        //gcc无法使用同时操作输入输出的二进制文件流
    if (!ofile)
    {
        cerr << "open error!" << endl;
        abort();
    }

/*
    if (!io_file)           //gcc无法使用同时操作输入输出的二进制文件流
    {
        cerr << "open io_file error!" << endl;
        abort();
    }
*/
    int i,m,num;
    cout << "Five staff:" << endl;
    for (i=0;i<5;i++)
    {
        cout << staf[i].num << " " << staf[i].name << " " << staf[i].age << " "
        << staf[i].pay << endl;
        ofile.write((char *)&staf[i],sizeof(staf[i]));     //写入文件
    }
    cout << "please input data you want insert:" << endl;
    ofile.seekp(0,ios::end);   //将输出文件位置标记移动到文件尾
    for (i=0;i<2;i++)
    {
        cin >> staf1.num >> staf1.name >> staf1.age >> staf1.pay;
        ofile.write((char *)&staf1,sizeof(staf1));      //写到文件尾
    }

    ofile.close();      //记得关闭文件流
    cout << "Seven staff:" << endl;

    ifstream ifile_1("staff.dat",ios::in|ios::binary);
    ifile_1.seekg(0,ios::beg);                               //定位到文件开头,不能省
    for (i=0;i<7;i++)                               //逐个读入并显示
    {
        ifile_1.read((char *) &staf[i],sizeof(staf[i]));     //读入一个职工数据
        cout << staf[i].num << " " << staf[i].name << " " << staf[i].age << " " << " " << staf[i].pay << endl;
    }
    //ifile_1.close();         //记得关闭文件流

    bool find_staff;            //检测是否找到
    cout << "enter number you want to search, enter 0 to stop:";
    cin >> num;
    while(num)
    {
        find_staff=false;       //一开始假设没找到
        ifile_1.seekg(0,ios::beg);      //定位于文件开头
        for (i=0;i<7;i++)
        {
            ifile_1.read((char *)&staf[i],sizeof(staf[i]));     //读入一个职工的数据
            if(num==staf[i].num)
            {
                m=ifile_1.tellg();      //返回当前字节位置
                cout << num << "is No." << m/sizeof(staf1) << endl;     //第几个职工
                cout << staf[i].num << " " << staf[i].name << " " << staf[i].age << " "
                << staf[i].pay << endl;
                find_staff=true;        //表示找到了
                break;

            }
        }

        if (!find_staff)
        {
            cout << "can't find " << num << endl;
        }
        cout << "enter number you want search,enter 0 to stop:";
        cin >> num;
    }

    ifile_1.close();            //记得关闭文件流
    cout << "Hello world!" << endl;
    return 0;
}

详细参考谭浩强C++上机操作,书中有误,可以参看本程序,在Code::Blocks运行。

你可能感兴趣的:(程序设计)