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.

i'm not sure try using seekp() instead of seekg()

Define "Doesn't really work" .. what are your results? What do you expect?

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, so show us how you're reading the file and how(where) you're resetting the file pointer

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

commented: very helpful and clear +3
commented: good one +4

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.