fwrite 4 char array, would write 7 instead of 4

  • A+
Category:Languages

The source code:

 main(void) {   unsigned char tmp[5] = {10, 10, 180, 255, 40};   FILE *ff = fopen("aa.bin", "w");   fwrite(&tmp, sizeof(char), 5, ff); } 

When executed and seeing Hex content of the file aa.bin, it looks like this:

0D 0A 0D 0A B4 FF 28

Why the value of 10 is written in two bytes (0D 0A) and char type holds only 1 byte. and what does (0D) means?

I am using G++ compiler (MinGW on Windows) and cpp11.


In ASCII, 10 is the character code for the newline '/n'.

Since you are operating in non-binary mode, the newline is interpreted as an actual newline and the standard library converts it to the platform-specific newline sequence, which is, on Windows systems, CR-LF (carriage return and line feed) or 0D 0A in hexadecimal.

Try to open the file in binary mode to skip the higher-level interpretation of the standard library and simply operate on bytes, not characters. Use "wb" for that purpose instead of "w".


As an aside, use tmp instead of &tmp. An array is implicitly converted to a pointer in certain situations, including the one at hand, it decays. &tmp is an actual pointer to an array, an unsigned char (*)[5] in this case. While both are equivalent in your specific case, this can turn problematic.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: