Hello everybody! I need to move the get pointer of a text file at the beginning so i wrote in my program the following line (knowing that in a binary file really works):

ifstream in;
      in.open("data.txt", ios::in);
       in.seekg(0, ios_base::beg);

but...in my text file doesn't really work. Is there a different way to move the get pointer in a text file? Thank you in advance for your time.

6 Years
Discussion Span
Last Post by vanalex

I get in my results the last record of the file continuously. So i assume that the get pointer didn't go back at the beginning of the file as i expected..


Ok, that's how i read my file:

ifstream in("data.txt", ios::in);
     if (!in) cout << "cannot open data.txt\n";
  //my file contains two columns of integer numbers, code and amount as i say below
 //so i'm counting how many records contain an amount greater than constant N
  //constant N is an integer value too
  int records = 0;
       do {
        in >> code >> amount;
        if (amount > N)
     } while (!in.eof());
     cout << "records = " << records << endl;
    in.seekg(0, ios_base::beg); //i'm putting the get pointer back to the beginning
     //then i'm doing some reading of the file again but i need to have the pointer
    //in the beginning

Your ifstream is in a fail state once you have exited the loop.
To make the stream functional again, use clear(), like so..

// Clear out any error state bits
// Now seekg() will work
in.seekg(0, ios_base::beg);

Then, don't use .eof() in a loop control, it will end up biting you.
There are many discussions at DaniWeb and elsewhere about why it is bad.

Instead, you could read from the file as follows ..

// Loop while reading of two values succeeds ..
  while(in >> code >> amount)
    if (amount > N)

  // Was the whole file read?
  if(in.eof() == false)
    // No, do something ...

To understand this better, modify your input file so that it contains non-numeric data and watch how your current program enters an infinite loop, for example:

1213 2232
4324 gotcha
432 34233

Votes + Comments
good one
very helpful and clear

Thank you so much for your answer mitrmkar you were more than clear...

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.