Reputation: 2101
In my following code , I am counting the number of words , lines and then calculating the size of text file . The first use of seekg
works fine after the first while
loop but after the second while
loop , it doesn't work . it gives values as shown in output .
#include <iostream>
#include <fstream>
using namespace std ;
int main(void)
{
fstream txtFile;
txtFile.open("test.txt");
if(txtFile.is_open())
{
printf("txt file is opened");
}
//number of words and lines in txt file
int w=0 , l =0 ;
int c , start , end;
string s;
while(1)
{
if(txtFile.peek() == -1)
break;
c = txtFile.get();
if(c != txtFile.eof())
w++;
}
txtFile.seekg(0,ios::beg);
while(getline(txtFile,s))
{
l++ ;
}
printf("no of words : %d , no of lines: %d\n",w,l);
//calculate the size of both the files
txtFile.seekg(0,ios::beg);
start = txtFile.tellg();
printf("%d\n",start);;
txtFile.seekg(0, ios::end);
end = txtFile.tellg();
printf("%d\n",end);;
return 0 ;
}
OUTPUT
txt file is opened
no of words : 128 , no of lines: 50
-1
-1
Upvotes: 1
Views: 1501
Reputation: 20083
The last input operation causes the fail bit to be set. If you call tellg
while this bit is set it too will fail. You need to call clear()
before you call tellg()
.
txtFile.clear(); // clear fail bits
txtFile.seekg(0,ios::beg);
Upvotes: 6