首页 > 解决方案 > 尝试从文件中读取对象并在正确获取一些记录后我的程序检测到 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我想将所有记录保存到一个对象数组中以便对数组进行排序

标签: c++file-handlingifstreameof

解决方案


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);

推荐阅读