c++多次将二进制文件读取到结构中
Reading Binary File into a struct too many times c++
我正在编写一个从二进制文件读写的程序,我的问题是,尽管文件(例如(中有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
相关文章:
- C++将文本文件中的数据读取到结构数组中
- 将内部带有矢量的结构保存/读取到二进制文件中
- 从 XML 中读取未指定结构的每个数据成员
- 如何读取没有数组或结构的 3 列文件
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- 嵌套结构,从由空行分隔的文件中读取数据
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 从只读内存中读取结构
- 为什么不读取带有指针的结构?
- 如何读取文件并将该文件分类为不同类型的数据,这些数据都存储在结构中的特定数组中
- 从文本文件中读取并输入到数组结构中,然后显示读取的数据C++
- 将文本文件读取到数组结构中
- 如何读取/查询文件系统和文件结构
- 从包含 IP 标头片段的二进制文件中读取结构的最佳方法是什么
- 使用结构读取和写入二进制文件
- 使用文件和结构读取数据并输出数据
- 使用结构 c++ 读取压缩文件 Gzread
- 结构读取C++
- 在 c++ 中使用消息结构读取/填充数据缓冲区的正确方法是什么?
- 将包含字符串属性的结构读取/写入二进制文件