Last record of file is repeated twice while using ifstream for opening of file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nazir hussain
    New Member
    • Jun 2013
    • 2

    Last record of file is repeated twice while using ifstream for opening of file

    //The out put of following code gives last record twice. What is wrong. Please help.
    Code:
    #include <iostream>
    #include <conio.h>
    #include <fstream>
    #include <cstdlib>
    using namespace std;
    
    struct abc
    {
           char code[5],name[15],address[20];
           int pay;
    };
    main()
    {
    
           abc rec;
           char op;
           int i=0;
           ifstream rrr("employees.dat",ios::in | ios::binary);
           if(!rrr)
           {
                      cerr<<("File opening error")<<endl;
                      getche();
                      exit(1); 
           } 
    
           while(!rrr.eof()){
    
                      rrr.read((char*)&rec,sizeof(struct abc));
                   
                      cout<<rec.code<<"\t"<<rec.name<<"\t"<<rec.address<<"\t"<<rec.pay<<endl;
                           }
           rrr.close();
           getche();
           return(0);
    }
    Last edited by Rabbit; Jun 2 '13, 04:54 AM. Reason: Please use code tags when posting code.
  • Oralloy
    Recognized Expert Contributor
    • Jun 2010
    • 988

    #2
    A Few Hints

    Hello Nazir,

    This is pretty obviously a homework, so I'm going to help you find the problem.

    Where the problem lies is in your process loop:
    Code:
           while(!rrr.eof()){
    
                      rrr.read((char*)&rec,sizeof(struct abc));
    
                      cout<<rec.code<<"\t"<<rec.name<<"\t"<<rec.address<<"\t"<<rec.pay<<endl;
                           }

    First: When is EOF (End Of File) going to be detected?

    HINT - your code is reading a fixed number of bytes from a binary file each time through the loop. What are the conditions that cause the EOF?

    Second: How will you reconstruct the process loop to handle EOF, when it is detected?

    HINT - what is the return value of the read method?

    Good Luck!
    Oralloy

    Comment

    • nazir hussain
      New Member
      • Jun 2013
      • 2

      #3
      First of all thank to Mr.Oralloy for help. Actually I am quite new person in learning c++ and have little background of programming. This exercise I copied from a book named "Programmin g with C++ (Aikman series)written by CM Aslam a pakistani author. I am sorry to say that I could not understand your reply. If you are kind enough to help me in detail or give me guidance for a good website from where I can learn c++ to prepare a windows application.
      I am again thankfull to you and wish u best wishes.

      Regards

      Nazir Hussain

      Comment

      Working...