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

Started by
3 comments, last by CC Ricers 16 years, 11 months ago
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;
}

Advertisement
You do realize that std::ios::trunc will truncate the file on opening, right?



jfl.
yes
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.
Also, you can do

while (data.tellg() < length)// It reaches right before the EOF // instead ofwhile(!data.eof() )


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

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

New game in progress: Project SeedWorld

My development blog: Electronic Meteor

This topic is closed to new replies.

Advertisement