Writing an integer as hex into a File using ofstream

Go To StackoverFlow.com

0

i have a function defined as follows:

void AddHeadCode(std::ofstream &ostream, size_t length){
ostream.write((char*)length, sizeof(length));
ostream.seekp(0x10L, std::ios::beg);
}

Now when this executes, it will fail obviously... as the char pointer will point nowhere. But i want the actual pointervalue written into the file. Like length = 19152 Then when I open up the file in an HEX Editor, I should find 0d4a there.

How can this be achieved in c++? Im kinda lost here...

2012-04-05 14:48
by xen


5

Take the address of your length variable, and pass that address to .write:

void AddHeadCode(std::ofstream &ostream, size_t length){
  // by popular demand, removed C-style cast
  ostream.write(reinterpret_cast<char*>(&length), sizeof(length));
  ostream.seekp(0x10L, std::ios::beg);
}

But, this is not usually refered to as writing an integer "as hex". This is sometimes referred to as writing an integer "as binary", or simply writing an integer.

Note that what you have done is not a portable practice. If you read the value back in on a different computer (or even on the same computer, but with a different compiler), you might not read in the same value.

2012-04-05 14:52
by Robᵩ
I would use reinterpret_cast<char*>(&length) - ipc 2012-04-05 14:55
Hah, thank you... i was blind : - xen 2012-04-05 14:55
@Rob: reinterpret - Anonymous 2012-04-05 14:58


0

Filestreams are tricky so I am uncertain about that but I use this for stringstreams:

std::basic_stringstream<wchar_t> oTmpStream;
oTmpStream << L"0x" << std::nouppercase << std::setfill( L'0' ) << std::hex << std::setw( 8 ) << iSomeValue

// or without fancy formatting;
oTmpStream << std::hex <<  iSomeValue
2012-04-05 14:58
by Adam
Ads