Why does the following code write four bytes when run on my local Windows machine using Visual C++, yet writes 4 extra 0 bytes when I upload to my school's Unix server?
unsigned long temp = 1025;
ofstream file("test", ofstream::binary);
file.write((char*)&temp, sizeof(temp));
Here is the result using xxd locally: 0104 0000
Here is the result on the Unix server: 0104 0000 0000 0000
Is this a problem with what mode I am opening the file in?
long
has implementation-defined size. Your Windows system uses a 32 bit (4 byte) long
(even 64 bit Windows uses 32 bit long
; otherwise it's rare to see on 64 bit OSes), while most if not all 64 bit UNIX-like systems I'm aware of have 64 bit (8 byte) long
s. Since you're writing out sizeof(temp)
bytes, and temp
is unsigned long
, you'll get different output sizes on different systems (you may also encounter byte order issues if you move from little endian to big endian machines).
If you need a consistent size, use the fixed width types from <cstdint>
, e.g. uint32_t
or uint64_t
.