I am trying to read file by following code
void main()
{
int i=0;
ifstream fout1 ("Aj.txt",ios::binary);
if (fout1.is_open())
{
while(fout1)
{
i++;
fout1.get(ch1);
cout<<ch1;
}
cout<<i;
fout1.close();
}
else
{
cout << "Unable to open file";
}
return 0;
}
here this code reads whole file but it goes into loop one extra time i.e if there are 4character in file then in loop it will iterate 5 time .how to correct it or overcome it.
That code reads until the
eofflag is set, but theeofflag is not set until a read actually fails. Which means whenfout1.get(ch1)reads the last character,eofis not set yet. So it displays, and checksfoutwhich is still good, so it re-enters the loop. Thenfout1.get(ch1)fails because of eof, and it displays the previous value ofch1again. The correct way to write that loop is: