fwrite & fread problem. What could cause it?

Started by
4 comments, last by MindWipe 22 years, 7 months ago
I have a problem. Sometimes when I save a map and load it it''s all screwed up. Here are my functions:
  
typedef struct  
{  
	unsigned char Look;
	unsigned char Feature;
}DataSquare;

Map::AllocateMemory()
{
	mData=new DataSquare[mWidth*mHeight];
	Reset();
}	 

Map::Reset()
{
	for(int i=0;i<mWidth*mHeight;i++){mData[i].Feature=0;mData[i].Look=0;}
}


Map::SaveMap(char *name)
{
	mFile=fopen(name,"wt");
	fprintf(mFile,"Name: %s\n",mName);
	fprintf(mFile,"Width: %i\n",mWidth);
	fprintf(mFile,"Height: %i\n",mHeight);
	fwrite(mData,sizeof(DataSquare)*(mWidth*mHeight),1,mFile);
	fclose(mFile);
}

Map::LoadMap(char *name)
{
	
	mFile=fopen(name,"rt");
	fscanf(mFile,"Name: %s\n",mName);
	fscanf(mFile,"Width: %i\n",&mWidth);
	fscanf(mFile,"Height: %i\n",&mHeight);
	AllocateMemory();
	fread(mData,sizeof(DataSquare)*(mWidth*mHeight),1,mFile);
	

	fclose(mFile);
}
  
Something causes all the tiles to move one to the left and change. Like if some bytes/bits are wrong at the beginning. Please help! /MindWipe "If it doesn''t fit, force it; if it breaks, it needed replacement anyway."
"To some its a six-pack, to me it's a support group."
Advertisement
I tried it some times. And it seems like when I save the look & feature get''s mixed up. But how can this be? And what can I do to fix it?

/MindWipe



"If it doesn''t fit, force it; if it breaks, it needed replacement anyway."
"To some its a six-pack, to me it's a support group."
Looks like you are mixing a Text Read and a Binary read in the same file. I would say investigate that first... If you want totally text output/input, try using a comma or tab delimitor.

-JT
this sounds like a big endian-little endian problem.
are you transfering the data file to a different machine?



Two things you should do: Don''t write labels for the data (Name, Width, Height) unless you''re actually going to use them to search for the data. The other thing (which has been mentioned) is to write in binary mode and not text.

[Resist Windows XP''s Invasive Production Activation Technology!]
I changed it to binary only. And now it seems to be working!

Thanks alot!

If I get this game sold I will surely donate money to GameDev.net

/MindWipe

"If it doesn''t fit, force it; if it breaks, it needed replacement anyway."
"To some its a six-pack, to me it's a support group."

This topic is closed to new replies.

Advertisement