c++多次将二进制文件读取到结构中

Reading Binary File into a struct too many times c++

本文关键字:结构 读取 二进制文件 c++      更新时间:2023-10-16

我正在编写一个从二进制文件读写的程序,我的问题是,尽管文件(例如(中有3个结构,但它会读取最后一个结构两次。这是我的代码:

结构体:

struct PARTICEPENTS
{
    char id1[10];
    char name1[11];
    char id2[10];
    char name2[11];
    int points;
};

写入:

void EnterParticipants()
{
    ofstream  PartFile;
    int i=1;
    PARTICEPENTS part;
    string temp="";
    PartFile.open("part.bin",ios::out|ios::binary);
    if(!PartFile){return;}
    cout<<endl<<endl <<"Enter 3 Participants:"<<endl;
    cout<<endl;
    while(i<=3)
    {               
        cout<<"the "<<i<<" couple"<<endl;
        cout << "tInsert the first id: " ;
        getline(cin, temp);
        strcpy(part.id1,stToChar(temp));
        cout << "tInsert the first name: ";
        getline(cin, temp);
        strcpy(part.name1,stToChar(temp));
        cout << "tInsert the second id:";
        getline(cin, temp);
        strcpy(part.id2,stToChar(temp));
        cout << "tInsert the second name:" ;
        getline(cin, temp);
        strcpy(part.name2,stToChar(temp));      
        part.points=0;
        PartFile.write((char*)(&part), sizeof(part));
        i++;
    }
    PartFile.close();
}

读取:

void DisplayFile()
{
    ifstream PartFile;
    PartFile.open("part.bin",ios::in|ios::binary);
    PARTICEPENTS filePart;
    if(!PartFile){return;}

    while(!PartFile.eof())
    {
        PartFile.read((char*)(&filePart), sizeof(filePart));
        cout<<left<<setw(12)<<filePart.id1<<left<<setw(12)<< filePart.name1 
                <<left<<setw(12)<<filePart.id2<<left<<setw(12)<<filePart.name2<<
                left<<setw(7)<< filePart.points <<endl;
    }
}

当我输入时:

111111111 Kim 111111111 Lori 
222222222 Roy 222222222 Tom 
333333333 Guy 333333333 Don 

屏幕的输出为:

111111111 Kim 111111111 Lori 0
222222222 Roy 222222222 Tom 0
333333333 Guy 333333333 Don 0
333333333 Guy 333333333 Don 0

我不知道为什么读不到最后一个结构之后就停止了。谢谢你的帮助。(抱歉我英语不好…(

while(!PartFile.eof())
{
    PartFile.read((char*)(&filePart), sizeof(filePart));
    cout<<left<<setw(12)<<filePart.id1<<left<<setw(12)<< filePart.name1 
            <<left<<setw(12)<<filePart.id2<<left<<setw(12)<<filePart.name2<<
            left<<setw(7)<< filePart.points <<endl;
}

这里的问题是,您正在读取三个条目,,但您还没有到达文件的末尾(当您读取第三个条目时,它是下一个条目(。当您第四次进入循环时,将到达文件末尾。

然后从

PartFile.read((char*)(&filePart), sizeof(filePart));

尝试将eof读入filePart,但失败了,因此没有任何内容读入。这意味着它仍将包含来自第三个循环的数据。这将再次显示。

您可以通过在显示数据之前确保PartFile.read已成功来修复它。

while(PartFile.read((char*)(&filePart), sizeof(filePart)))
{
    // PartFile.read((char*)(&filePart), sizeof(filePart));
    cout<<left<<setw(12)<<filePart.id1<<left<<setw(12)<< filePart.name1