954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem with fstream write() function

Hi

I have a problem with a code I made, some save editor for some game.
The code suppose to write 2 bytes to a specific offset in some file.
The file's short integers are saved as little endian.
everything works fine, but when one of the integers equal 10, it is saved as another number.

my function to write the short integers is:

void writeInt(int n, int pos, fstream* file)
	{	
		char tmp[2];
		tmp[0] = n & 0xff;
		tmp[1] = (n >> 8) & 0xff;
		file->seekp(pos, ios::beg);
		file->write(tmp, 2);
	}


I call this function in the function:

void writeData()
	{
		fstream saveFile(saveFilePath);

		//player copper
		writeInt(PCopper, 169, &saveFile);
		//player silver
		writeInt(PSilver, 171, &saveFile);
		//player gold
		writeInt(PGold, 173, &saveFile);
		//player platinum
		writeInt(PPlatinum, 175, &saveFile);
		//bank copper
		writeInt(BCopper, 191, &saveFile);
		//bank silver
		writeInt(BSilver, 193, &saveFile);
		//bank gold
		writeInt(BGold, 195, &saveFile);
		//bank platinum
		writeInt(BPlatinum, 197, &saveFile);

		//close file
		saveFile.close();
	}


for example if I'll enter 10 in all the fields, every variable except the platinum ones will be saved as 2570, which equals 256*10+10.
but if I enter any other number but 10 it will be saved as it is.

I debugged my code and all the values are correct when they reach the write function:

file->write(tmp, 2);


I have no idea what can cause this problem, it doesn't make sense to me that only the value 10 cause problems.

Any help would be very appreciated!

yoni0505
Light Poster
28 posts since Jan 2010
Reputation Points: 10
Solved Threads: 2
 

If you are going to perform unformatted I/O, open the stream in binary mode (use std::ios_base::binary). Or else, text mode escape sequence translations will take place.

vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 
If you are going to perform unformatted I/O, open the stream in binary mode (use std::ios_base::binary). Or else, text mode escape sequence translations will take place.

Thank you, that was the problem.

yoni0505
Light Poster
28 posts since Jan 2010
Reputation Points: 10
Solved Threads: 2
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: