learn through suffering C language learn through suffering 
C 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/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-type pointer variable = fopen(FileName, Mode);
fclose(FILE-type pointer variable);

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.

Mode string Purpose
r Reading. Fails if file does not exist.
r+ Reading and writing. Fails when no file exists.
w Write. Create an empty file even if one exists.
w+ Reading and writing. Even if a file exists, it creates an empty file.
a Additional write. Create the file if it doesn't exist.
a+ Additional read/write. Create if file does not exist.

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
At first glance, the fclose function doesn't seem particularly necessary for this program alone. However, the fclose function plays an important role, so it must not be forgotten.

Modern computers can run multiple applications simultaneously.
If different applications were to overwrite the same file at the same time,
it would become unclear which changes should be reflected.

Therefore, files opened for writing using the fopen function
are locked to prevent other software from modifying them.
The fclose function is necessary to release this lock,
making the file available for use by 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(file pointer, Write string, 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 execution result would be as follows.

Contents of the test.txt file before execution
100


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 execution result would be as follows.

Contents of the test.txt file before execution
test100


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


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


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.
CSVs saved in Excel tend to get complicated, so it's not that simple...


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. line break
  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

Loading comment system...