c++ - 尝试从文件中读取对象并在正确获取一些记录后我的程序检测到 eof,留下了许多记录
问题描述
我正在尝试将文件中的记录读入对象。但是在正确读取一些记录后,程序检测到文件结尾,即使文件中有更多记录。我已经使用同一类的对象在文件上写了记录,但我不明白出了什么问题。
这是我的代码-
int main()
{
long int n=0;
class_name objt[100];
ifstream fl;
fl.open(filename);
cout<<"Scanning file"<<endl<<"Please Wait"<<endl;
while(true)
{
fl.read((char*)&objt[n], sizeof(objt[n]));
if(fl.eof())
{
cout<<endl<<"END OF FILE"<<endl<<"Press any key to continue";
cin.get();
break;
}
n++;
}
fl.close();
cout<<endl<<"Scanning Complete!"
这是我正在使用的课程-
class class_name
{
public:
char name[20];
double cn ;
int code;
int unit;
};
PS我想将所有记录保存到一个对象数组中以便对数组进行排序
解决方案
If you are going to do binary I/O then you must open your file in binary mode (for both reading and writing)
ifstream fl;
fl.open(filename, ios_base::binary);
推荐阅读
- javascript - 如何根据 localStorage 状态选中/取消选中复选框
- javascript - 如何在不影响内部元素的情况下背景图片缩放动画
- flutter - 滚动列表视图时容器 BlendMode 消失 - Flutter
- flutter - 如何从 dart 文件中获取上下文
- animation - 当我运行这个示例 pygame 代码时,DOS 窗口出现并突然消失,无需等待任何用户输入
- ios - 需要 Swift 二进制框架的外部依赖项
- javascript - 打开单击的选项卡并关闭其余选项卡
- flutter - 颤振图像裁剪器未显示要裁剪的图像
- python - 如何使用 blosc 压缩的 numpy 数组存储元数据
- javascript - 如果与另一个精灵的位置相同,则停止精灵的移动