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

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class bank
{
protected:
char receive[20];
public:
}

int main()
{
fstream file;
strcpy(receive,"hello");
file.open("binary.my",ios_base::in | ios_base::out | ios_base::binary | ios_base::app);
file.write(reinterpret_cast<char*>(&receive),sizeof(receive));
file.close();
return 0;
}

That code doesn't compile for me. 'receive' is a member variable of 'bank' and you're not addressing it as such. You also need a semicolon after the class definition.

Yes, this code is broken. First, receive is not declared in the main function. You must first declare an object of type bank. Secondly, you won't be able to use strcpy to write data directly into the c-string bank::receive unless you make a dangerous assumption. Most compilers place the private members of a class at the very beginning of the objects allocated memory. It is often possible to access this privare memory by reading or writing data directly from the memory address of the object. I don't think this sort of allocation is in the c++ spec, however, so I think this sort of hack can result in undefined behavior.

I'd like to point out that you can make your class much more user friendly by adding some functionality. First, you could make your bank constructor take a static character array as an argument to instantiate its receive c-string:

class bank
{
protected:
    char receive[20];
public:
    bank( const char* recStr ); // Implement this to copy recStr into receive
};

Secondly, you could write a function in bank called write that knows how to write its data to a binary ostream:

class bank
{
protected:
    char receive[20];
public:
    bank( const char* recStr ); // Implement this to copy recStr into receive
    write( ostream& out );  // Implement this to write receive to the ostream
};

I also must make one strong suggestion. Since you are using the c++ Standard Template Library already by utilizing fstream, you should go ahead and use c++ strings. These are much safer and easier to use than char arrays, and, as far as I'm concerned, make your code much more readable.

Good luck!

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.