Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.


binary files

This topic is 5911 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I was trying out some binary file i/o stuff and started having a problem. Let me show the code:
#include <iostream.h>
#include <fstream.h>
#include <string.h>

class CTest

	void SetFloat(float x) { Flot = x; }
	float GetFloat() { return Flot; }
	void SetNum(int n) { Num = n; }
	int GetNum() { return Num; }

	float Flot;
	int Num;

void main()
	CTest InputTester;
	CTest OutputTester;

	ofstream OutF("MoreTest.dat", ios::binary);
	OutF.write((char*)(&InputTester), sizeof(&InputTester));

	ifstream InF("MoreTest.dat", ios::binary);

	cout << InputTester.GetFloat() << "\n";
	cout << InputTester.GetNum() << "\n";
	cout << OutputTester.GetFloat() << "\n";
	cout << OutputTester.GetNum() << "\n";
The output works fine with the Floats, but not with the ints. The last cout displays: -858993460. I''m not quite sure what exactly is wrong, but if anyone could help I''d be grateful.

Share this post

Link to post
Share on other sites
There are two reasons I can think of right now that could result in such output:

1) You''re outputting an unsigned int as a regular int (try casting)
2) You''re doing floating point math with ints without very proper casting

Hope this helps,

Share this post

Link to post
Share on other sites

are WRONG. You''re passing a pointer to sizeof(), which is 4 bytes--enough to hold the int, but not the float.

Take the & off those, or better yet, change them both to sizeof(CTest).

Share this post

Link to post
Share on other sites
You really shouldn''t use class objects in that manner. But the reason it''s not working is because you''re doing sizeof(&InputTester), which is getting the size of a POINTER to the object, which is 4 bytes (the size of a float). You need sizeof(InputTester).

That being said, you should have a method in the class that accepts the file stream to read/write from as an argument, and that method would read/write the values of the data to the already opened stream. This way you don''t worry about the details of how the object instance is represented in memory.

Share this post

Link to post
Share on other sites
This very same problem was asked and thoroughly answered just
a few days ago. Please use the search feature...

Kami no Itte ga ore ni zettai naru!

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!