When i am writing a content into a file as a binary, it's quite stored in a binary format but, my problem is during the reading.After the reading i am receiving the content two times. Actually i don't know whether it writes or reads two times.
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's been a while since I've done file IO in C/C++, but doesn't it require that you read the EOF before file.eof() is set? What I believe is happening is this:

1. while (!file.eof()) // first time here, so it's not EOF
2. file.read(...blah...) // read the file into the buffer
3. cout << pass // display the buffer
4. while (!file.eof()) // we haven't read the EOF, so this is still not EOF
5. file.read(...blah...) // read the file into the buffer. Since there is nothing left, nothing is read, but EOF is now set
6. count << pass // since nothing was read, nothing changed in the buffer so it still has whatever it had before
7. while (!file.eof()) // Now it is EOF, so we exit.

You need to do a read before the while loop:

file.read(reinterpret_cast<char*>(&pass),sizeof(pass));
while (!file.eof()) {
    cout << pass;
    file.read(reinterpret_cast<char*>(&pass),sizeof(pass));
}
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.