Skip to main content
GameDev.net gamedev.net
🔒 Locked

Writing binary data to a file

Started by AlmightyBUU Mar 9, 2003 at 2:51 AM 2 replies 150+ views
Original Post
AlmightyBUU
AlmightyBUU
Perhaps i''m doing something astoundingly stupid, but why aren''t these two programs working properly? writer:
  
#include <fstream>
#include "tile/Tile.h"

using namespace std;
int main()
{
	ofstream fout("test.map",ios::binary);
	if(!fout) cout<<"Error, can''t open test.map"<<endl;
	Tile t;
	t.x=100;t.y=250;t.w=54;t.h=123;t.img="nice";
	for(int i=0;i<100;i++){t.x=i; fout.write((char*)&t,sizeof t);}

	return 0;
}
  
reader:
  
#include<fstream>
#include"tile/Tile.h"

using namespace std;
int main()
{
	ifstream fin("test.map");
	if(!fin) cout<<"Error";
	Tile t;

	while(!fin.eof()){ fin.read((char*) &t,sizeof t); cout<<t.x<<endl;}

	return 0;
}
  
Tile.h:
  
class Tile
{
	public:
	Tile();

	char *img;
	int x,y;
	int w,h;
};

Tile::Tile(){;}
  
When i run the writer, then run the reader, i get this output:
0
1
2
3
4
5
6
7
8
9
10
11
12
-100663296
-100663296
-100663296
 
With those last lines being repeated about 60 times more.
smart_idiot
smart_idiot
1) You want to read the file back in binary mode, too.
2) Writing pointers to a file (Tile::img) is an extremely bad idea.
3) More things can go wrong than just reaching the end of a file.
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other
AlmightyBUU
AlmightyBUU
1) Yeah, the ios::binary was what was messing me up. Whoops =/

2) How would I write a "string" to a file instead?

3) I realize that, but it''s a simple demo.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.