Jump to content
  • Advertisement
Sign in to follow this  
Thirthe

[c++/fstream] seekg(0) not working?

This topic is 4149 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hey when i use fstream and seekg(0) twice, tellg() will return -1 and the program will not work properly( will not pass at data.is_open() ) is there any reason for this to happen? thank you very much.
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>

using namespace std;
int main()
{
	string vektor;
	int i=0,v=0,n=0;
	char vnos[100];
	char znak;
	fstream data("d:\\a.txt", ios::in|ios::out|ios::trunc);

	if(data.is_open())
	{
		while(i<5)
		{
			cin.getline(vnos,200);
			data<<vnos<<endl;
			i++;
		}
	}else cout<<"Napaka Datoteke!"<<endl;

    cout<<"HAY!1 "<<data.tellg()<<endl;

	data.seekg( 0 );

    cout<<"HAY!2 "<<data.tellg()<<endl;

	if(data.is_open())

	{    cout<<"HAY!3 "<<data.tellg()<<endl;

		while(!data.eof() )
		{
			getline(data,vektor);
			cout<<vektor<<endl;
		}

	}else cout<<"Napaka Datoteke!"<<endl;

    cout<<"HAY!4 "<<data.tellg()<<endl;

	data.seekg(0);

    cout<<"HAY!5 "<<data.tellg()<<endl;

	i=0;

	if(data.is_open())
	{

    cout<<"HAY!6 "<<data.tellg()<<endl;

		while(!data.eof())
		{

			znak=data.get();
			i++;


			if((znak=='\n') || (znak==' ') || (znak=='\0'))
			{
				n++;
			}
			cout<<znak;

		}
	}else cout<<"Napaka Datoteke!"<<endl;
	v=i-n;

	cout<<endl<<"vsi znaki"<<i<<endl;
	cout<<"drugi znaki"<<n<<endl;
	cout<<"vsi znaki"<<v<<endl;

	data.close();

  system("pause");
  return 1;
}

Share this post


Link to post
Share on other sites
Advertisement
OK, the problem is:

while(!data.eof() )
{
getline(data,vektor);
cout<<vektor<<endl;
}


Since you've gone till the EOF, the stream is now in a bad() state. You need to clear() it before you can seekg():

cout<<"HAY!4 "<<data.tellg()<<endl;

data.clear();
data.seekg(0);



jfl.

Share this post


Link to post
Share on other sites
Also, you can do


while (data.tellg() < length)

// It reaches right before the EOF
// instead of

while(!data.eof() )




You would need to store the length of the file first.


data.seekg(0,ios::end);
int length = textstream.tellg();

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!