I have a problem when i am writing a content into a files as a binary format.I noticed, that it writes the content two times into the file.
Here is the code.

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class store
{
protected:
char pass[50];
public:
fstream file;
store();
~store();
void writing();
void reading();
};
store::store()
{
file.open("binary.dat",ios::in | ios::out | ios::app | ios::binary);
}
store::~store();
{
file.close();
}
int main()
{
store b;
b.writing();
b.reading();
return 0;
}
void store::writing()
{
char buf[] = "hello";
strcpy_s(pass,sizeof(buf),buf);
file.write(reinterpret_cast<char*>(&pass),sizeof(pass));
}
void store::reading()
{
file.seekp(0,ios_base::beg);
while(!file.eof())
{
file.read(reinterpret_cast<char*>(&pass),sizeof(pass));
cout<<pass;
}
}

>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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.