I have some code for Windows that opens a file as an fstream
object using ios::in|ios::out|ios::binary
. I'm trying to peek
1 byte, change it and write it back to the file in the same position. This is the relevant code (note: _SH_DENYWR is the Windows share mode so I can write to the file but other processes cannot):
this->m_File.open(filename, ios::in | ios::out | ios::binary, _SH_DENYWR);
...
// Using peek here causes all subsequent writes to fail
// even though peek returns the correct value and is not
// peeking at the EOF
BYTE byte = this->m_File.peek();
BYTE high = binPattern[0].High;
BYTE low = binPattern[0].Low;
BYTE finalByte = byte;
if (high != this->WILDCARD && (byte >> 4) != high)
finalByte = (finalByte & 0x0f) | (high << 4);
if (low != this->WILDCARD && (byte & 0x0f) != low)
finalByte = (finalByte & 0xf0) | low;
this->m_File.write((char*)&finalByte, sizeof(BYTE));
// This seekp resets something in the stream and allows the next write to succeed
this->m_File.seekp(this->MAGIC_OFFSET, ios::beg);
this->m_File.write((char*)&this->PATCH_MAGIC, sizeof(DWORD));
...
What am I doing wrong with peek
and write
?