seekg

i have a question about seekg.

from my understanding myfile.seekg(2, ios::end);

will position the pointer to the second last element and start reading from there, but for some reason I am not getting any output.


afile.txt is just a txt file filled with some random lines.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  #include <iostream>
#include <fstream>
# include <sstream>


using namespace std;

int main() {

	string line;

	streampos begin, end;
	ifstream myfile("afile.txt", ios::binary);
	begin = myfile.tellg();
	//myfile.seekg(-2, ios::end);

    myfile.seekg(2, ios::end);

	//myfile.seekg(2, ios::beg);

	while (getline(myfile, line))
	{
		cout << line << endl;

	}



	end = myfile.tellg();
	myfile.close();
	cout << "size is: " << (end - begin) << " bytes.\n";


	system("pause"); 

	return 0;
}
You need to use a negative offset.

 
myfile.seekg(-2, ios::end);

Note that whitespace characters such as newlines and spaces are also counted. Text files are usually terminated with a newline (even if you cannot see it in a text editor). On Windows newlines normally consist of two characters (CR+LF), so don't be surprised if the loop doesn't give you any visible output.
Last edited on
thanks Peter,

i just tried myfile.seekg(-3, ios::end);

and it worked.



how come the size is -1 bytes ... should it not be a positive value , because end is larger than end ?
tellg() returns -1 on failure.

The reason it fails is because when getline fails it will set the failbit (myfile.fail() == true) which will cause all read operations that follow (including tellg()) to automatically fail. In order to use the file like normally again you need to call clear() first.

 
myfile.clear();
Last edited on
#include <iostream>
#include <fstream>
# include <sstream>


using namespace std;

int main() {

string line;

streampos begin, end;
ifstream myfile("afile.txt", ios::binary);
begin = myfile.tellg();
//myfile.seekg(-2, ios::end);

//myfile.seekg(2, ios::end);

//myfile.seekg(2, ios::beg);

while (getline(myfile, line))
{
cout << line << endl;

}



end = myfile.tellg();


myfile.clear();

myfile.seekg( 0, ios::beg);

//myfile.seekg(-10, ios::end);


while (getline(myfile, line))
{
cout << line << endl;

}


myfile.close();
cout << "size is: " << (end - begin) << " bytes.\n";


system("pause");

return 0;
}
Topic archived. No new replies allowed.