Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fwrite 4 char array, would write 7 instead of 4

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.

like image 210
Osama Saadallah Al-Ta'ai Avatar asked May 27 '18 11:05

Osama Saadallah Al-Ta'ai


People also ask

What does fwrite mean in C?

(Write Block to File) In the C Programming Language, the fwrite function writes nmemb elements (each element is the number of bytes indicated by size) from ptr to the stream pointed to by stream.

Where does fwrite write to?

The fwrite() writes to an open file.

How to use fwrite()?

The fwrite() function writes the data specified by the void pointer ptr to the file. ptr : it points to the block of memory which contains the data items to be written. size : It specifies the number of bytes of each item to be written. n : It is the number of items to be written.

Does fwrite write in binary?

fwrite(obj,A,' precision ') writes binary data with precision specified by precision . precision controls the number of bits written for each value and the interpretation of those bits as integer, floating-point, or character values. If precision is not specified, uchar (an 8-bit unsigned character) is used.


1 Answers

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.

like image 176
cadaniluk Avatar answered Sep 21 '22 18:09

cadaniluk