fwrite fails to write value 10 (0x0A)

c, fwrite

Solution

Your file was opened in text mode so CRLF translation is being done. Try:

fopen("test.bin","wb");

Problem

I was experimenting on creating BMP files from scratch, when I found a weird bug I could not explain. I isolated the bug in this minimalist program: ``` int main() { FILE* ptr=NULL; int success=0,pos=0; ptr=fopen("test.bin","w"); if (ptr==NULL) { return 1; } char c[3]={10,11,10}; success=fwrite(c,1,3,ptr); pos=ftell(ptr); printf("success=%d, pos=%d\n",success,pos); return 0; } ``` the output is: ``` success=3, pos=5 ``` with hex dump of the `test.bin` file being: ``` 0D 0A 0B 0D 0A ``` In short, whatever value you put instead of `11` (0x0B), `fwrite` will write it correctly. But for some reason, when `fwrite` comes across a `10` (0x0A) - and precisely this value - it writes `0D 0A` instead, that is, 2 bytes, although I clearly specified 1 byte per write in the `fwrite` arguments. Thus the 3 bytes written, as can be seen in the `success` variable, and the mysterious `5` in the `ftell` result. Could someone please tell me what the heck is going on here...and why 10, why not 97 or 28?? Thank you very much for your help! EDIT: oh wait, I think I have an idea...isn't this linked to \n being 0A on Unix, and 0D 0A on windows, and some inner feature of the compiler converting one to the other? how can I force it to write exactly the bytes I want?

Original source