Site Search

Hello, I'm Duck.

Now, we learned how to handle text files from this article. In C language, you can handle not only text files but also binary files.

string output

First, let's output the character string "altima" to the file "out.txt" in text file format.

 

Output result (out.txt)

 

It displayed correctly. Now, what about in binary format? Let's try outputting it the same way.

 

Setting the file mode to "wb" allows you to open the file in binary format, and changing the output function to fwrite allows you to write data in binary format.

 

Output result (out.txt)

 

The output is correct, but what's the difference between this and a text file?

deal directly with numbers

In binary format, you can directly handle numerical values such as int type. In the previous example, we used a char array, but let's try using an int array. Also, let's try inputting numbers instead of characters.

 

Output result (out.txt)

 

For some reason it is not displayed properly. What happened?

 

I thought I was doing something wrong, so I asked my supervisor.

 

Then I was told, "Check with a binary editor."

 

I did some research and it seems that using a binary editor allows you to see the file as a sequence of bits in hexadecimal. Now let's take a look at the output result with a binary editor.

 

In this editor, two digits represent one byte. Here, the int type is 4 bytes, so eight digits form a single unit.

It's a little hard to understand, but if you color-code each 4 bytes as shown in the figure, it should be easy to understand. Look at the first blue line.

 

Normally, the low byte is stored first. Therefore, when rearranging these 4 bytes, it will be as follows.

 

64 00 00 00 → 0000 0064 (hex) = 100 (decimal)

The number 100 that you entered properly is reflected.

If you read in the same way, you can see that the data you entered is 200, 300, 400, 500.

 

A binary file containing numerical data cannot be read in text format because the data is entered directly.


Also, if you don't know what type of numeric value it is, you can't handle the data correctly.

In this example, if you look at the out.txt file, which contains binary numbers, you cannot read it unless you know that it contains five integer values.

When reading binary files, you need to pay attention to their format.

as a side note

One question remains. At the beginning, when dealing with strings, why didn't it change?

When you write a string, the characters are converted to ASCII, as shown in the diagram below, and their values are written. If you open this in a text editor, you can read it as characters in the same way.

Therefore, writing in binary format produced no difference compared to writing in text format.

The advantage of writing in binary format seems to be evident when writing numbers such as integers.