1
   int main(){
    base pers;
    fstream of;
    of.open("multiple");
    of.read((char*)&pers,sizeof(pers));
    while(!of.eof())
    {
        pers.show();
        of.read((char*)&pers,sizeof(pers));
    }
    of.close();
    return 0;
    }

//multiple is a previosly created file which consists some data //pers is a object of base class

Akash Roy
  • 37
  • 7
  • You need to write `read` twice because you use `eof()` as loop condition. If you would use `read()` as the loop condition itself, it will be only in one place. – Yksisarvinen Aug 12 '20 at 15:59
  • @Yksisarvinen thanks for helping ,but i want the explanation why using eof() is making such thing? – Akash Roy Aug 12 '20 at 16:11
  • @AkashRoy, making such thing? What do you mean? – Geno C Aug 12 '20 at 16:12
  • @GenoC like when i run the full program it's actully going with never ending loop if i just don't use the read() before while loop. – Akash Roy Aug 12 '20 at 16:15
  • This doesn't address the question, but get in the habit of initializing objects with meaningful values rather than default-initializing them and immediately overwriting the default values. In this case, that means changing `fstream of; of.open("multiple");` to `fstream of("multiple");`. Also, you don't need to call `of.close();`. The destructor will do that. – Pete Becker Aug 12 '20 at 16:55
  • `while(!of.eof())` -> `while(!of.read((char*)&pers,sizeof(pers)))`. As to why `eof()` forces you to write `read()` twice, it's because eof bit is only set after *unsuccessful* read. This means you have to first read, then check for eof and then use the read value. If you use result of read operation as condition, you combine the read and check steps, so you don't have to duplicate the read (the loop body will always be run after a successful read). – Yksisarvinen Aug 12 '20 at 21:15

0 Answers0