binary files

Started by
4 comments, last by Laroche 21 years, 9 months ago
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
{
public:
	CTest(){}
	~CTest(){}

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

private:
	float Flot;
	int Num;
};

void main()
{
	CTest InputTester;
	CTest OutputTester;
	
	InputTester.SetFloat(5.5f);
	InputTester.SetNum(13);

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

	ifstream InF("MoreTest.dat", ios::binary);
	InF.read((char*)(&OutputTester),sizeof(&OutputTester));
	InF.close();

	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.
Check out my music at: http://zed.cbc.ca/go.ZeD?user_id=41947&user=Laroche&page=content
Advertisement
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,
Crispy
"Literally, it means that Bob is everything you can think of, but not dead; i.e., Bob is a purple-spotted, yellow-striped bumblebee/dragon/pterodactyl hybrid with a voracious addiction to Twix candy bars, but not dead."- kSquared
sizeof(&InputTester)
sizeof(&OutputTester)

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).
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.
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!
神はサイコロを振らない!
Thanks, I appreciate the help

Next time I''ll use the search first.
Check out my music at: http://zed.cbc.ca/go.ZeD?user_id=41947&user=Laroche&page=content

This topic is closed to new replies.

Advertisement