Hello, this is Duck.
Well, I learned how to handle text files in this article. The C language can handle binary files as well as text files.
Outputting Strings
First, let's output the string "altima" to the file "out.txt" in the text file format.
Output result (out.txt)
The output is displayed correctly. How about in binary format? Let's try the same output.
If the file mode is set to "wb", the file can be opened in binary format, and by changing the output function to "fwriteW, data can be written in binary format.
Output result (out.txt)
The output is correct, but what is the difference between this and a text file?
Dealing with numbers directly
The binary format can directly handle numeric values such as int type. In the previous sample, it was an array of char type, but let's try it with an array of int type. Also, try inputting numeric values instead of characters.
Output result (out.txt)
For some reason, it does not display well. What is wrong?
I thought I made a mistake and consulted with a senior colleague.
Then he told me, " Try checking with a binary editor.
I found out that a binary editor allows you to view the file in hexadecimal bit order. So let's take a look at the output result with a binary editor.
In this editor, 2 digits represent 1 Byte. In this case, the int type is 4 Bytes, so 8 digits are a group. It is a little confusing, but it can be understood by color-coding each 4 Byte as shown in the figure. Let's look at the first blue line.
Normally, the lower bytes are stored first. Therefore, if we rearrange these 4 Bytes, we can see the following.
64 00 00 00 00 → 0000 0064 (hex) = 100 (decimal)
The value of 100 is reflected.
Reading the same way, we can see that the data we entered as 200, 300, 400, and 500 is also included.
So a binary file with numbers entered is not readable in text format because the data is entered as is.
Also, you need to know what type of number it is to handle the data correctly.
In this example as well, when you look at the out.txt file containing binary numbers, you cannot read it unless you know that there are five numbers of type int.
When reading a binary file, we need to be careful about its format.
By the way.
One question remains. At the beginning, why didn't it change when dealing with strings?
When writing a string, the characters are converted to ASCII and their values are written, as shown in the figure below. If this is opened in a text editor, it can be read as a character in the same way.
Therefore, there is no difference between writing in binary format and writing in text format.
The advantage of writing in binary format seems to be demonstrated when writing numbers such as int type.
New Engineer's Blush Blog Article List