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.
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.
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.
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.
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.
This program will create a file named test.txt.
It was only opened this time, so it's naturally empty inside.
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.
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.
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.
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.
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.
When you run this program, the contents of the test.txt file will be as follows.
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.
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.
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.
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.
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.
Also, if you list multiple numbers separated by commas,
Multiple variables can also be loaded.
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...
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) isThis 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.




