>it writes the content two times into the file.
Close. It writes the content once, but because of a common bug you read it twice.
>while(!file.eof())
This is the bug. eof only returns true after you've tried and
failed to read from the file. Using it as a loop condition without any other tests in the body is a fencepost error.
Here are two common solutions. If your reading function returns a stream state, you can use it directly as the condition:
while (file.read(pass, sizeof pass))
cout<< pass;
Or you can double up the eof test and avoid processing after a failed read:
while (!file.eof()) {
file.read(pass, sizeof pass);
if (!file.eof())
cout<< pass;
}
Obviously the former is preferred because it's shorter, cleaner, and generally perceived as easier to follow.
Reputation Points: 6442
Solved Threads: 1391
Bad Cop
Offline 11,807 posts
since Sep 2004