在我的以下代码中,我计算字数、行数,然后计算文本文件的大小。第一次使用seekg
在第一个while
循环之后工作正常,但在第二个while
循环之后,它不起作用。它给出的值如输出所示。
#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