Archived

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

Raloth

problem using file streams

Recommended Posts

I'm trying to use file streams to save my maps from my editor, but ios::binary is giving me problems. It doesn't seem to output everything in binary. It also causes the end of the file to be a repeat of the beginning or something. I don't know how to explain it, it's so weird . Can anyone help me out? saving:
		ofstream file;
		file.open(filepath,ios::out | ios::binary);
		unsigned short mapsize = (unsigned short)landscape.GetSize();
		unsigned char** tilemap = landscape.GetTilemap();
		float** heightmap = landscape.GetHeightmap();
		file << mapsize;
		for(int i=0;i<mapsize;i++) {
			for(int j=0;j<mapsize;j++) {
				file << tilemap[i][j];
			}
		}
		for(int i=0;i<mapsize+1;i++) {
			for(int j=0;j<mapsize+1;j++) {
				file << heightmap[i][j];
			}
		}
		
		file.close();
loading:
   	ifstream file;
	file.open(filepath,ios::in | ios::binary);
	unsigned short size;
	file >> size;
	
	unsigned char** tilemap;
	float** heightmap;
	tilemap = new unsigned char*[size];
	heightmap = new float*[size+1];
	for(int i=0;i<size;i++) {
		tilemap[i] = new unsigned char[size];
		for(int j=0;j<size;j++) {
			file >> tilemap[i][j];
		}
	}
	for(int i=0;i<size+1;i++) {
		heightmap[i] = new float[size+1];
		for(int j=0;j<size+1;j++) {
			file >> heightmap[i][j];
		}
	}
	
	file.close();
[edited by - Raloth on October 5, 2003 10:17:08 PM]

Share this post


Link to post
Share on other sites
i believe there are read() and write() member funtions of the stream.

but, is there any reason in particular that you need to outout this in raw binary, rather than human-readable?

Share this post


Link to post
Share on other sites
Maybe you're trying to make it too complicated?


struct foo {
int x;
char y;
};

foo thing = { 10, 'x' };
ofs.write((char*)&foo, sizeof(foo));


This would write the struct to a file, which could be read back just as easy using almost identical code. It kinda' depends on what you're writing. In your case, what with pointers and all, you may need to develop a file "format."

[edited by - cubicool on October 5, 2003 12:32:53 AM]

Share this post


Link to post
Share on other sites
Opening a file in binary mode means newlines will not be translated into CR+LF/CR/LF (depending on your platform) but be read/written literally, as is necessary for binary IO.

IOStream''s operator<< and operator>> do formatted IO, not binary IO.

For binary IO, use read() and write().


[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]

Share this post


Link to post
Share on other sites