473,506 Members | 17,176 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Saving a binary file help.

Hi all

I've just started learning about saving files. I got bit of a problem. The
following code gives me an error about incompatible types. (Cannot covert
from class character to char *). I would appreciate it if anyone could
either help me out, or direct me to an online resource site that has
information on saving/loading classes. I have found several tutorials, but
they either do not really help (saving text files) or are too difficult for
me to understand. Thanks
class character
{
public:
character();
character(string charName);
virtual ~character();

string getCharName();

private:
string name;
int age;
};

void saveFile(character* characterFile)
{

ofstream writeFile;

writeFile.open("game.dat", ios::binary);

writeFile.write((char *)characterFile, sizeof(character));

writeFile.close();

}

Jul 19 '05 #1
7 7509
G-Factor wrote:
Hi all

I've just started learning about saving files. I got bit of a problem. The
following code gives me an error about incompatible types. (Cannot covert
from class character to char *). I would appreciate it if anyone could
either help me out, or direct me to an online resource site that has
information on saving/loading classes. I have found several tutorials, but
they either do not really help (saving text files) or are too difficult for
me to understand. Thanks
class character
{
public:
character();
character(string charName);
virtual ~character();

string getCharName();

private:
string name;
int age;
};

void saveFile(character* characterFile)
{

ofstream writeFile;

writeFile.open("game.dat", ios::binary);

writeFile.write((char *)characterFile, sizeof(character));
DANGER above ... sizeof(character) returns the size of the character
class NOT THE SIZE OF THE STRING.....

I suggest you add a method

operator const & string () const
{
return name;
}

and then you can

writeFile << * characterFile;


writeFile.close();

}


Jul 19 '05 #2
"Gianni Mariani" <gi*******@mariani.ws> wrote in message
news:3F**************@mariani.ws...
I suggest you add a method
operator const & string () const
{
return name;
}
and then you can
writeFile << * characterFile;


And what about the 'age' field ?
I guess G-Factor wanted to save both 'age' and 'name' field.

Fabio
Jul 19 '05 #3

"Fabio" <fa*************@libero.it> wrote in message
news:be**********@newsreader.mailgate.org...
"Gianni Mariani" <gi*******@mariani.ws> wrote in message
news:3F**************@mariani.ws...
I suggest you add a method
operator const & string () const
{
return name;
}
and then you can
writeFile << * characterFile;


And what about the 'age' field ?
I guess G-Factor wanted to save both 'age' and 'name' field.

Fabio


Yes, I want to save the entire class.
Jul 19 '05 #4
Gianni Mariani wrote:
G-Factor wrote:
Hi all

I've just started learning about saving files. I got bit of a
problem. The following code gives me an error about incompatible
types. (Cannot covert from class character to char *). I would
appreciate it if anyone could either help me out, or direct me to an
online resource site that has information on saving/loading classes.
I have found several tutorials, but they either do not really help
(saving text files) or are too difficult for me to understand. Thanks
class character
{
public:
character();
character(string charName);
virtual ~character();

string getCharName();

private:
string name;
int age;
};

void saveFile(character* characterFile)
{

ofstream writeFile;

writeFile.open("game.dat", ios::binary);

writeFile.write((char *)characterFile, sizeof(character));
DANGER above ... sizeof(character) returns the size of the character
class NOT THE SIZE OF THE STRING.....


Well, that's only part of the problem. It will of course include the
size of the string object, but that object probably contains a pointer
to the actual string data. With that cast, only the pointer itself
would be written to the file, _not_ the data it points to.
If you don't have a good reason to write the data in binary form, don't.
It's quite unportable (You can't write the structure on a PC and read
it on a MAC, and maybe not even on the same PC using a different
compiler), produces lots of problems (e.g. you can't use classes that
contain pointers or virtual member function - wrt the C++ standard, you
might only have a chance with PODs AFAIK) and in many cases isn't worth
it.
I suggest you add a method

operator const & string () const
You probably meant:

operator const string & () const
{
return name;
}

and then you can

writeFile << * characterFile;
What about the age?


writeFile.close();

}


Jul 19 '05 #5

"G-Factor" <ge***@iprimus.com.au> wrote in message
news:3f********@news.iprimus.com.au...
And what about the 'age' field ?
I guess G-Factor wanted to save both 'age' and 'name' field.

Fabio


Yes, I want to save the entire class.

IMHO you can overload the operator << to save object data into file
(serialize) and >> operator to load object data from file (deserialize)
I wrote a simple example without error-checks so please take it as a pure
sample.

class character
{
public:
character() {};
character(std::string charName) : name(charName) {}
virtual ~character() {};

std::string getCharName();

private:
friend std::ostream& operator << (std::ostream& s, const character& c);
friend std::istream& operator >> (std::istream& s, character& c);

std::string name;
int age;
};

std::ostream& operator << (std::ostream& s, const character& c)
{
std::string::size_type stype = c.name.length();
s.write((char*) &stype, sizeof(stype) );
s.write(c.name.c_str(),c.name.length());
s.write((char*) &c.age,sizeof(c.age));
return s;
}

std::istream& operator >> (std::istream& s, character& c)
{
std::string::size_type stype = 0;
s.read((char*) &stype, sizeof(stype) );
char* pstr = new(std::nothrow) char[stype+1];
s.read(pstr,stype);
pstr[stype] = '\0';
c.name = pstr;
delete [] pstr;

s.read((char*) &c.age,sizeof(c.age));
return s;
}

int main()
{
std::ofstream ofile("game.dat", std::ios_base::out | std::ios_base::trunc
| std::ios::binary);

character c1("pippo");

ofile << c1;
ofile.close();

std::ifstream ifile("game.dat", std::ios_base::in | std::ios::binary);

character c2;

ifile >> c2;
ifile.close();

return 0;
}

I hope this simple code can help you.
Fabio
Jul 19 '05 #6

"Thomas Matthews" <th*************@sbcglobal.net> wrote in message
news:3F**************@sbcglobal.net...
3. The binary format of the fields _may_ not be portable across
platforms or compiler implementations.
So why, in your sample, don't you use any signature to identify memory model
(little-endian or big-endian) while saving the integer field ?
4. DO NOT USE OPERATOR<<. The operator is for formatted data,
not unformatted binary data.


Thanks. I forgot that important point.

Fabio
Jul 19 '05 #7
Fabio wrote:
"Thomas Matthews" <th*************@sbcglobal.net> wrote in message
news:3F**************@sbcglobal.net...
3. The binary format of the fields _may_ not be portable across
platforms or compiler implementations.

So why, in your sample, don't you use any signature to identify memory model
(little-endian or big-endian) while saving the integer field ?


Imagine the size of adding an additional byte for every multibyte
value (not including text).

One could save the Endianess at the beginning of the file.
That would be one flag instead of many.

If you need to deal with Endianism, you could read the value
into a buffer then pass the buffer through an endianism filter.
The filter would swap bytes if necessary. The filter could
be activated based on the header information.

Endianess is no problem if and only if the file stays on
the same platform.

If the file is to be used across platforms, try using
ASCII formatted numbers. Most systems can convert an ASCII
number into native format. The C++ language even has
facilities for this.

Otherwise one has to flag the platform specifics such as
endianess, bits per value and floating point format.

Also, my sample was not complete, but enough to give
you an idea and basis to build upon. I didn't supply
code for buffer support and inheritance.

4. DO NOT USE OPERATOR<<. The operator is for formatted data,
not unformatted binary data.

Thanks. I forgot that important point.

Fabio

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 19 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
3733
by: Kevin Knorpp | last post by:
Hello. I need to be able to extract the data from the attached file (or any file in the same format) so that I can work with the data in PHP. I'm fairly comfortable with using PHP with...
2
1915
by: news.hku.hk | last post by:
i have a binary file "myfile.bin", its output of "od -t x1 myfile.bin" is: 0000000 7f 45 4c 46 01 02 01 and longer. i want the output to screen be: 7f 45 4c 46 01 02 01 i try to write the...
4
5620
by: Jens Mittag | last post by:
Hi! In my code, I have an array of a structure, which I want to save to a binary file. When the array is just created, everything works fine, but when I change contents of the array, saving...
5
5299
by: Neo | last post by:
Hello: I am receiving a Binary File in a Request from a application. The stream which comes to me has the boundary (Something like "---------------------------39<WBR>­0C0F3E0099" without the...
4
2192
by: Greg | last post by:
Using the HttpWebRequest I'm downloading a PDF file and am trying to save it to the hard drive, but it keeps ending up corrupt (according to adobe acrobat). I know the PDF file isn't corrupt...
5
4318
by: Phil Kelly | last post by:
Hi I need to write the contents of a structure to a binary file - there is one string and 2 integers, but I can't seem to figure out how to write the data correctly. If I am simply writing...
2
6522
by: Bill Nguyen | last post by:
I need sample code to insert binary file (mappoint map file) into a varbinary column using VB.NET. Please help! Thanks Bill
2
10698
by: Peter Bassett | last post by:
I need to process data in many binary files. If I open the file in Wordpad the data is readable. If I save the file as a Text Document I can process the .txt file in VB via the Open and Line Input...
1
12304
by: Chunekit Pong | last post by:
How to save a Base64 encoded string to a binary file For instance, the following XML tag stores the binary data in a Base64 encoded string <data>TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx<data> ...
0
7218
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7103
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7307
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
7021
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7478
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5614
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
3177
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1532
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
755
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.