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

Reading and writing text files

File Handling
Up until now, all input and output has been displayed on the screen.
It's convenient because you can see the results right away when they're displayed on the screen.
However, the results displayed on the screen disappear when the program ends.
It's not practical to display a massive amount of data on a screen.

In cases like this, it's common to **save the data to the file**.
Data saved as a file is stored on disk.
It won't disappear and is easily copied or edited.

Here, we will explain how to read and write files in C.
File opening and closing
The steps for manipulating files from a program generally follow this order.

Instructions for File Manipulation
Open file -> Read and write to file -> Close file

In essence, file operations require opening and closing files.
Therefore, C has functions available for opening and closing files.
The opening function is the `fopen` function, and the closing function is the `fclose` function.
To use this function, you need to include stdio.h.
The usage of each function is as follows.

Functions for opening and closing files.
FILE型のPointer variables = fopen(File名, モード);
fclose(FILE型のPointer variables);

A filename is, as the name suggests, a filename.
You can specify it by full path or by name alone.

Mode refers to a string that describes the purpose for which a file is being opened.
The mode accepts one of the following six string types.

モード文字列 目的
r 読み込み。FileがないHourは失敗。
r+ 読み書き。FileがないHourは失敗。
w 書き込み。Fileがあっても空のFileを作る。
w+ 読み書き。Fileがあっても空のFileを作る。
a 追加書き込み。FileがないHourは作る。
a+ 追加読み書き。FileがないHourは作る。

The FILE type is a new type we haven't encountered before, but it's essentially a structure.
The fopen function returns a pointer to a FILE structure containing file information.
This pointer will only be used as a file identifier from now on.
You will not perform pointer-specific operations or use structure members.
Conventionally, pointer variables of type FILE are called file pointers.

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

Source code
#include <stdio.h>

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

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

The role of fclose
It appears that the fclose function isn't strictly necessary for this particular program.
However, the fclose function has an important role, so don't forget about it.

Modern computers can run multiple apps simultaneously.
もし、同じFileを同Hourに別々のAppsで書き換えてしまうと、
I'm not sure which one to reflect.

そこで、fopenfunctionで書き込みができるように開いたFileには、
"It's locked to prevent modification by other software."
The `fclose` function is necessary to release the lock and make the file accessible to other applications.

Writing to a file
There are many different functions available for writing text to a file.
Within that, there's a function similar to the familiar printf function, called fprintf.
The usage of the fprintf function is as follows.

fprintf function
fprintf(FilePointer, 書き込み文字列, variable・・・);

It's virtually identical to the printf function, except for the need to specify a file pointer.
The specified string will be written to a file, not to the screen.
The following program writes the string "Hello,world" to the file test.txt.

Source code
#include <stdio.h>

int main(void)
{
    FILE *file;
    file = fopen("test.txt", "w");
    fprintf(file, "Hello,world");
    fclose(file);
    return 0;
}

When you run this program, the contents of the test.txt file will be as follows.
The test.txt file will be created in the same folder as the executable.

"Post-execution 'test.txt'"
Hello,world

You can also write variable values, just like with the printf function.
The following program writes the value of variable i to the file test.txt.

Source code
#include <stdio.h>

int main(void)
{
    int i = 100;
    FILE *file;
    file = fopen("test.txt", "w");
    fprintf(file, "%d", i);
    fclose(file);
    return 0;
}

When you run this program, the contents of the test.txt file will be as follows.

"Post-execution 'test.txt'"
100


Reads and additions.
If opened in read-only mode, using write functions will have no effect.
When opened in append mode, data will be added to the end of the original file.

Reading from file
There are also many different kinds of functions for reading text from files.
There is a fscanf function, similar to the familiar scanf function.
It functions the same as the scanf function, except for specifying the file pointer at the beginning.

The `scanf` function reads input from the keyboard, so its execution results in the program waiting for input.
The fscanf function reads the text from a file starting from the beginning.
The following program reads and displays the leading numbers from the file test.txt.

Source code
#include <stdio.h>

int main(void)
{
    int i;
    FILE *file;
    file = fopen("test.txt", "r");
    fscanf(file, "%d", &i);
    fclose(file);
    printf("%d\n", i);
    return 0;
}

The output of this program depends on the contents of the test.txt file.
"If the contents of the test.txt file were as follows, the result would be as follows."

Contents of the "test.txt" file before execution
100


Execution results
100

"When using the %d specifier as in the example above, any non-numeric text will be ignored."
"If the contents of the test.txt file were as follows, the result would be as follows."

Contents of the "test.txt" file before execution
test100


Execution results
100

Using the %s specifier for string input allows you to read the entire string.
However, it will only read up to that point if spaces are included.

Contents of the "test.txt" file before execution
test100


Execution results
test100

Also, if you list multiple numbers separated by commas,
Multiple variables can also be loaded.

Source code
#include <stdio.h>

int main(void)
{
    int i, j;
    FILE *file;
    file = fopen("test.txt", "r");
    fscanf(file, "%d,%d", &i, &j);
    fclose(file);
    printf("i = %d : j = %d\n", i, j);
    return 0;
}


Contents of the "test.txt" file before execution
23,56


Execution results
i=23 : j=56

Files with values and strings listed and separated by commas (,) are called CSV format.
It is known as a versatile file format that can be handled by spreadsheet software such as Excel.
The above program also allows you to read CSV files saved in Excel using your own program.
エクセルでSaveしたCSVは複雑になりがちなのでそれほど簡単ではありませんが・・・


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