I need to write to a file directly (file format/extension doesn't matter). What I want to be able to do is, eg write A to it, and if I opened the file with a hex editor, it would display A, aka the value 10 in decimal.
#include <iostream>
int main()
{
std::ofstream fout("myfile.ext", std::ios::binary);
std::ofstream::char_type byte = 10; //or = 0xA
fout.put(byte);
}
Well, if you write 'A'
to the file, I'd expect the hex editor to show 41.
But let's say we have an int x = 0xa;
, then the way to write that to a file is:
int x = 0xa;
ofstream out("myfile.txt", ios::out|ios::binary);
out.write((char *)&x, sizeof(x));
out.close();
Note that this code isn't highly portable, since size of int
and the order of bytes within an integer can change from architecture to architecture.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.