Can I change a file stream object's read position in C++? I mean I have a file with a series of integers separated by a newline character. Can I read the first five integers into some variables and then move the read position back to read the fifth integer one more time?

You can move the position (using seekg) either by an offset, or to a previous point (that was saved by tellg). Unless your file is very strictly formatted, you probably want the latter. So in your case, call tellg to get the file position before reading the fifth line, then use seekg to return to that position.

Though if you're saving those integers into variables, why do you need to read them again? They're already in memory for you. :icon_rolleyes:

Well, actually i was trying to read two integers at a time, perform some comparison and then write them to another file! :-/ It was kinda like performing bubble sort without using array.
Anyway, thanks a lot for help! :)

Hi,
can anyone plz take a look at my code? I think it should work, but it didn't.
Here's my code:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	ifstream IN;
              
for ( int n = 0; n <= 2; n++)
{
               IN.open("remain1.txt");

	int min = 0, min2,a;

	cout << "position before read= " << IN.tellg() << endl; 
	
	IN >> min;
	while(!IN.eof())
	{
		IN >> a;
		if (a < min) min = a;
	}

	
	IN.seekg(0);
	cout << "position after reset = " << IN.tellg() << endl; 

	IN.close();
	}
return 0;
}

Basically, what my code would do is to move the reading position in a file back to the beginning after it reach eof. And it should do that three times. But actually, it seems to work ONLY once~ Can anyone tell me why? :-/

Thanks! :twisted:

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.