Click to See Complete Forum and Search --> : Strange behaviour of _write() function


Adam Oldak
April 23rd, 2003, 03:32 PM
Recently I have come across something a bit suprising for me. After execution of such a code:

unsigned long size = 9;
_write(handle, &size, sizeof(unsigned long));

four new bytes appear in the file indicated by 'handle' variable:
09 00 00 00

If the first line of the code is:
unsigned long size = 11;

the bytes are:
0B 00 00 00

However if
unsigned long size = 10;

There are five bytes:
0D 0A 00 00 00

The same situation happens with any hexadecimal number with the youngest byte of 0A

What`s going on? Why are there 5 bytes, not 4? Is there any way (except of checking the youngest byte) to avoid this problem, and make it 4 bytes long? - it's essencial for the project I'm working on.

Thanks!

Adam Oldak.

Yves M
April 23rd, 2003, 05:50 PM
It's simply because you open the file in "text" mode instead of binary mode. In text mode any character 10 (\n) will be translated as the sequence 13, 10 (\r\n). So the solution is to open the file in binary mode.