Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change stream from text mode to binary in C++?

In a game I'm making I need to read a map from a file. Assuming some of the data in the beginning is written in characters, but the tile map is written in binary, I would open the file in text mode then switch it to binary mode once it reaches the tile data.

Is there an easy, or standard, way of changing an ifstream from text mode to binary mode while keeping the same position in the file? This also applies to the writting part, I will need to start writting into the file using characters, then change to binary mode.

EDIT: I'm using text mode to make this readable and to read strings of unknown size. For example, this line:

map-name=TestMap

I'd read this with

getline( mapFile, attribute, '=' );
getline( mapFile, mapName, '\n' );

How would I read this in binary mode if there won't be newline characters?

like image 989
aslg Avatar asked Nov 06 '25 21:11

aslg


2 Answers

The mode is established when the file is opened, and cannot be changed later. If there is any binary data in the file, you must use binary mode. But where is the problem? You can read text in binary mode; line endings might appear a bit strange (but not if you also wrote it in binary mode), but otherwise, there should be no problem as long as the binary data actually is text.

like image 197
James Kanze Avatar answered Nov 09 '25 12:11

James Kanze


If you are responsible for writing the files as well, the simplest (and perhaps sanest) solution might be to write two files.

One in text, for text you wish to be human readable.

And the second as binary, for things like maps. In fact that way you could have one binary map file for each map.

like image 27
doctorlove Avatar answered Nov 09 '25 12:11

doctorlove