读取二进制文件并将其输出到控制台窗口

时间:2013-01-14 09:22:35

标签: c++ debugging binaryfiles

 void createtask(char filename[MAX])
{
char filenameb[MAX];
strcpy(filenameb,filename);
strcat(filenameb,".dat");

fstream writeb;
fstream readb;

writeb.open(filenameb,ios::out | ios::binary);

task t;
int nooftask;
cout<<"-----------------------------------"
    <<endl
    <<endl
    <<"Creation of task"
    <<endl
    <<endl
    <<"How many task ?: ";
cin>>nooftask;

cin.clear();
cin.ignore(200,'\n');

for(int i=1;i<=nooftask;i++)
{
    t.task_no=i;

    cout<<endl
        <<"Information for task "
        <<i
        <<endl
        <<endl;


    cout<<"Title for assessment: ";
    cin.getline(t.task_title,200);


    cout<<"Weight (%): ";
    cin>>t.task_weight;

    cout<<"Full mark upon: ";
    cin>>t.task_fullmark;

    cin.clear();
    cin.ignore(200,'\n');

    cout<<"Description: ";
    cin.getline(t.task_descrip,200);

    writeb.write(reinterpret_cast <const char *>(&t), sizeof (t));

    cout<<t.task_descrip
        <<endl
        <<t.task_fullmark
        <<endl
        <<t.task_no;


}

writeb.clear();



writeb.close();

cout<<endl
    <<endl
    <<"The creation of task file is completed"
    <<endl
    <<endl
    <<"The summary of creation"
    <<endl
    <<endl;

//summarytask(readb,filenameb);

    //start
    cout<<"Summary of task"
    <<endl
    <<endl;

    readb.open(filenameb,ios::binary | ios::in);


while (readb.read(reinterpret_cast < char *>(&t), sizeof (t)) ); // problem is here
{
    cout<<endl
        <<endl
        <<t.task_no // programme only output the last record in binary file
        <<endl
        <<t.task_title;//

}

readb.close();
//end


}

一切正常,但我似乎无法将二进制文件中的所有记录输出到控制台窗口。我出于某种原因只能输出二进制文件中的最后一条记录,谢谢

1 个答案:

答案 0 :(得分:0)

我补充说;

while (readb.read(reinterpret_cast < char *>(&t), sizeof (t)) ); // there shouldnt
//be a ; after the while