The so-called binaries and text files are not different for letters, they are ASCII values that store the letters. Can cause difference is the number and some layout with the symbol format.
- A number stores the value of the number in a binary file, and the text file first treats the number as a character amount and converts it to a new digital re-storage according to the ASCII code table;
- An example of a typographic symbol is a newline character, a binary file is just a newline character, and a text file is a newline character plus a carriage return;
So the simple way to distinguish between text files for each character is to do the ASCII conversion, and the binary file will only make the necessary ASCII conversion of letters, the number is directly stored.
Let's talk about how to really implement binary file creation:
It's not what we think it's possible to set ios::binary when opening a file, but also pay attention to the output function:
When using << output, it is actually converted to a text file output. That is, if you output a number, it is first converted to the corresponding ASCII value as a string store. The way to output a binary file in this way is to trick the computer--casting an array such as double,int into a char array. Note that you cannot be a single variable, because the double one is 4 bytes, char is 1 bytes, and the array size changes while the array is converted so that the data is not lost, but the variable is bound to lose data during the casting process. When converted directly to Char, it is not actually converted, and the output char variable is not converted, so it deceives the << operator so that we can output a number as Char instead of the ASCII conversion. The actual code is as follows:
ofstream file("E:/BaiduYunDownload/data.txt" ,ios_base::binary|ios_base::trunc); double a[4]={16.7,2.4,42.3,56.7}; int i; if(!file.good()) { printf("Cannot open the file\n" ); return0; } for(i=0;i<sizeof (a);i++){ file<<((char *)a)[i]; }
Another method is the write function, the theory is the same, all rely on casting to char type variable to avoid the ASCII conversion
C + + output binary files and text files