Trouble with eof()
Hi all,
I'm having some difficulty understanding the difference in
interpratation of the fstream's eof() method.
I basically try and read a file in and count the number of
characters I read in, using the code in the main routine I
always get one more (count1) than the second count I get
from using the code in load file.
Even when the file is empty, the eof() for the first loop
round returns true, which i believe is somewhat incorrect.
void loadfile(const std::string& file_name, std::string& buffer)
{
std::ifstream file(file_name.c_str(), std::ios::binary);
if (!file) return;
buffer.assign(std::istreambuf_iterator <char>
(file),std::istreambuf_iterator <char>());
file.close();
}
void main()
{
std::string file_name = "data.dat";
std::ifstream file(file_name.c_str(),std::ios::binary);
if (!file) return false;
unsigned int count = 0;
while (!file.eof())
{
file.get();
count++;
}
file.close();
std::string buffer;
loadfile(file_name, buffer);
std::cout << "count1: " << count << std::endl;
std::cout << "count2: " << buffer.length() << std::endl;
}
The only solution i can think up of at this time is to check eof once
i've
called get. if eof is true then to break, like so:
while (true)
{
file.get();
if (file.eof()) break;
count++;
}
I was just hoping someone on this list could explain to me
why eof doesn't work the way i'm thinking it should be working,
and if there is anyplace in the standards that describes how
eof should work, when it should return true and when it should
return false.
any help would be very much apprecaited.
regards
Sherrie
PS: I've tested it with gcc 3.4 and vs 2003 they both seem to
give the same results.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]