MMGameslogo  MMGames
TwitterSharebutton  FacebookSharebutton   
learn through sufferingC Language
learn through sufferingC Language

Reading and writing binary files

Text and binary
Files come in many varieties, but a fundamental distinction is...
There's a difference between text and binary.

All files are essentially binary files.
Literally translated, "binary" means "base-2" or "binary number system".
A binary file is, as the name suggests, a file recorded in binary code.
In short, it refers to a file containing only numerical data.

In contrast, a text file is a file that contains only strings of characters.
Even strings are represented by numbers within a computer.
Text files are, at their core, binary files as well.
However, since text files are recorded as strings,
It is easy to make corrections in a text editor or similar application.

Binary files can also be viewed and edited with specific editors, but
Since all the data is a collection of numbers,
I don't understand the meaning at all, even after looking at the content.
However, it is small in size and fast because numbers are written directly.

Generally, if ease of handling is required, a text file,
Binary files are often used when high speed is required.
File opening and closing
Whether it's text or binary, the fundamental steps for file manipulation remain the same.
Binary files are also opened and closed using the fopen and fclose functions.
The method for specifying the file name and mode is exactly the same.
However, when opening binary files, you must append 'b' to the end of the mode string.

If you understand what I've explained so far, you should be able to open and close binary files.
The following program is an example of opening a file named test.dat for writing.

Source code
#include <stdio.h>

int main(void)
{
    FILE *file;
    file = fopen("test.dat", "wb");
    fclose(file);
    return 0;
}

This program will create a file named test.dat.
It was only opened this time, so it's naturally empty inside.

Can be used interchangeably.
実際には、バイナリで開いてもテキストデータを読み書きできますし、
While the reverse is possible, it would introduce several inconveniences, particularly regarding line breaks.

Writing to a file
To write numeric values directly to a file, use the `fwrite` function.
The usage of the fwrite function is as follows.

fwrite function
fwrite(書き込むvariableaddress, 1項目のサイズ, 項目数, FilePointer);

Store the numerical value entered into a variable and then specify the address of that variable.
The size of an item can be determined using the sizeof operator.
If you're just writing variables, the number of items can be 1 for now.
The following program writes the number 100 to the file test.dat.

Source code
#include <stdio.h>

int main(void)
{
    int buf = 100;
    FILE *file;
    file = fopen("test.dat", "wb");
    fwrite(&buf, sizeof(buf), 1, file);
    fclose(file);
    return 0;
}

This program will write values to the test.dat file, but...
This value cannot be seen with a typical text editor.
You need a binary editor to view binary files.
The following is an editor I frequently use.

hgBed http://www.vector.co.jp/soft/win95/util/se081906.html

When you open a file with a binary editor, it looks like this:
In modern compilers, an int is 32 bits, so it's written using 8 bytes.

Opened "test.dat" in a binary editor.
64 00 00 00

In a binary editor, numbers are displayed in hexadecimal.
Therefore, the number 100 is displayed as 64.

Little-endian and big-endian
In mathematics, converting 100 to hexadecimal yields 0064.
However, when viewed in a binary editor, it shows 6400.
This is a characteristic of Intel-compatible CPUs, referred to as little-endian.
この表現では、hexadecimalを2桁ずつに区切り逆の順番でSaveします。

Some CPUs also adopt a system that represents data in the order of hexadecimal digits.
This is known as big-endian.

リトルエンディアンはわかりにくく見えますが、
先頭に意味があるnumericsが来やすいという利点があり、データ読み取り上有利なため、
Little-endian is the dominant byte order in modern systems.

You can write the entire array at once using the fwrite function.
The method is simply to specify an array instead of variables.
The following program writes values to an array.

Do you remember?
array名は、式の中では先頭addressになるので、&をつけません。


Source code
#include <stdio.h>

int main(void)
{
    int buf[] = {10, 100, 1000, 10000};
    FILE *file;
    file = fopen("test.dat", "wb");
    fwrite(buf, sizeof(buf), 1, file);
    fclose(file);
    return 0;
}

When you run this program, values will be written to test.dat.
When you open a file with a binary editor, it looks like this:

Opened "test.dat" in a binary editor.
0A 00 00 00 64 00 00 00 E8 03 00 00 10 27 00 00

Reading from file
To read numerical values directly from a file, use the fread function.
The usage of the fread function is as follows.

fread function
fread(読み込むvariableのPointer, 1項目のサイズ, 項目数, FilePointer);

It becomes clear that its usage is the same as the fwrite function.
The following program reads integer values from the file test.dat.

Source code
#include <stdio.h>

int main(void)
{
    int buf;
    FILE *file;

    file = fopen("test.dat", "rb");
    fread(&buf, sizeof(buf), 1, file);
    fclose(file);

    printf("%d\n", buf);

    return 0;
}

The outcome of this program depends on the contents of the test.dat file.
"It would read as follows if written by the program created in section three."
"If the contents of the test.dat file were as follows, the execution result would be as follows."

Make the binary editor "test.dat" like this.
0A 00 00 00


Execution results
10

You can also load an array in a manner similar to the fwrite function.

Choosing Between Binary and Text Files
The advantage of binary files is that they offer fast read/write speeds and smaller file sizes.
Therefore, files that you want to handle as quickly as possible, such as images, videos, and audio, are essentially binary files.

Conversely, a benefit of text files is that they are easy for humans to edit.
When you're in a difficult situation, saving things as a text file can be surprisingly useful and easy to manage.



About This Site

Learning C language through suffering (Kushi C) is
This is the definitive introduction to the C language.
It systematically explains the basic functions of the C language.
The quality is equal to or higher than commercially available books.

Part 0: Program Overview
  1. What is a program?
Chapter 3: Displaying on the Screen
  1. String Display
  2. newline character
  3. Practice Problem 3
Chapter 4: Displaying and Calculating Numbers
  1. Display of numbers
  2. Basic calculations
  3. Numeric types
  4. Practice Problem 4
Chapter 6: Input from the Keyboard
  1. input function
  2. The fear of input
  3. Practice Problem 6
Chapter 9: Repeating a Fixed Number of Times
  1. Iterative sentence
  2. How Loops Work
  3. Practice Problem 9
Chapter 10: Repeating Without Knowing the Number of Times
  1. Unspecified loop
  2. Input validation
  3. Practice Problem 10
Chapter 13: Handling Multiple Variables at Once
  1. Handling multiple variables collectively.
  2. Arrays
  3. Practice Problem 13
Chapter 19: Dynamic Arrays
  1. Create arrays freely.
  2. Practice Problem 19