C language learned by suffering
C language learned by suffering
Reading and writing text files
File Handling
Until now, all inputs and outputs have been displayed on the screen.
This is because it is convenient to display the results on the screen so that the results can be understood immediately.
However, the results displayed on the screen disappear when the program is finished.
It is also impractical to display huge amounts of data on the screen.
In such cases, it is usual to save the data in a file.
Data saved as a file is stored on disk so that it can be
It will not disappear and can be easily copied and re-edited.
This section describes how to read and write files in C.
This is because it is convenient to display the results on the screen so that the results can be understood immediately.
However, the results displayed on the screen disappear when the program is finished.
It is also impractical to display huge amounts of data on the screen.
In such cases, it is usual to save the data in a file.
Data saved as a file is stored on disk so that it can be
It will not disappear and can be easily copied and re-edited.
This section describes how to read and write files in C.
File Open/Close
The procedure for manipulating files from a program is generally performed in the following order.
In other words, file operations require opening and closing files.
Therefore, the C language provides functions to open and close files.
The open function is the fopen function and the close function is the fclose function.
To use this function, the inclusion of stdio.h is required.
The usage of each function is as follows.
A file name is just what it sounds like.
It can be specified by full path or by name only.
The mode can be one of the following six strings
The FILE type is a new type that has never appeared before, but its identity is the structure.
When the fopen function is executed, a pointer to the FILE type with file information is returned.
This pointer is only to be used thereafter as an identifier of the opened file, so
No pointer-specific operations are performed or structure elements are used.
By convention, a pointer variable to type FILE is called a file pointer.
Once you know what we have described so far, you can open and close files.
The following program is an example of opening a file named test.txt for writing.
When this program is run, a file named test.txt is created.
In this case, the contents are empty, of course, because we just opened it.
Procedure for manipulating files
Open file -> Read/write to file -> Close file
In other words, file operations require opening and closing files.
Therefore, the C language provides functions to open and close files.
The open function is the fopen function and the close function is the fclose function.
To use this function, the inclusion of stdio.h is required.
The usage of each function is as follows.
Functions to open and close files
Pointer variable of type FILE = fopen(filename, mode);
fclose(pointer variable of type FILE);
A file name is just what it sounds like.
It can be specified by full path or by name only.
The mode is a string that indicates the purpose for which the file is to be opened.
The mode can be one of the following six strings
Mode String | Purpose |
---|---|
r | Read. Fails when there is no file. |
r+ (for a file) | Read/write. Fails if the file does not exist. |
w | Writing. Creates an empty file even if a file exists. |
w+ (for a file) | Read/Write. Create an empty file even if the file exists. |
a | Additional writes. Create when there is no file. |
a+ (a+) | Additional read/write. Create when file is not available. |
The FILE type is a new type that has never appeared before, but its identity is the structure.
When the fopen function is executed, a pointer to the FILE type with file information is returned.
This pointer is only to be used thereafter as an identifier of the opened file, so
No pointer-specific operations are performed or structure elements are used.
By convention, a pointer variable to type FILE is called a file pointer.
Once you know what we have described so far, you can 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;
}
When this program is run, a file named test.txt is created.
In this case, the contents are empty, of course, because we just opened it.
Role of fclose
From this program alone, it may seem that the fclose function is not particularly necessary.
However, the fclose function has an important role to play.
On modern PCs, multiple applications can run at the same time.
If the same file is rewritten by different applications at the same time
It is difficult to know which one to reflect.
Therefore, files opened for writing with the fopen function must be marked with
The software is locked so that it cannot be rewritten by other software.
The fclose function is required to release the lock so that it can be used by other applications.
However, the fclose function has an important role to play.
On modern PCs, multiple applications can run at the same time.
If the same file is rewritten by different applications at the same time
It is difficult to know which one to reflect.
Therefore, files opened for writing with the fopen function must be marked with
The software is locked so that it cannot be rewritten by other software.
The fclose function is required to release the lock so that it can be used by other applications.
Writing to file
Many types of functions are available to write text to a file.
Among them is the fprintf function, which is very similar to the familiar printf function.
The usage of the fprintf function is as follows
Its usage is exactly the same as the printf function except that it specifies a file pointer.
The specified string is written to a file, not to the screen.
The following program writes the string Hello,world to the file test.txt.
After running this program, the contents of the test.txt file will look like this
The test.txt file is created in the same folder as the executable file.
Like the printf function, it can also write the value of a variable.
The following program writes the value of variable i to the test.txt file.
After running this program, the contents of the test.txt file will look like this
Among them is the fprintf function, which is very similar to the familiar printf function.
The usage of the fprintf function is as follows
fprintf function
fprintf(file pointer, write string, variable ...);
Its usage is exactly the same as the printf function except that it specifies a file pointer.
The specified string is 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;
}
After running this program, the contents of the test.txt file will look like this
The test.txt file is created in the same folder as the executable file.
test.txt" after execution
Hello,world
Like the printf function, it can also write the value of a variable.
The following program writes the value of variable i to the test.txt file.
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;
}
After running this program, the contents of the test.txt file will look like this
test.txt" after execution
100
For loading and appending
When opened in read mode, nothing happens when using functions for writing.
When opened in append mode, data is appended to the end of the original file.
When opened in append mode, data is appended to the end of the original file.
Read from file
There are many different types of functions that read text from files, but the
There is a fscanf function similar to the familiar scanf function.
Its usage is the same as that of the scanf function, except that a file pointer is specified at the beginning.
The scanf function reads from the keyboard, so it waits for input when executed, but the
The fscanf function reads the text of a file from the beginning.
The following program reads and displays the first number from the test.txt file.
The results of running this program depend 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
If the %d specifier is used, as in the example above, non-numeric text is ignored.
If the contents of the test.txt file were as follows, the execution result would be as follows
The entire string can be read by using the %s specifier used for string input.
However, if spaces or other characters are included, only that much will be read.
You can also use a comma (,) to separate multiple numbers in a row.
It is also possible to read multiple variables.
A file of numbers and strings separated by commas (,) like this is called a CSV format.
It is known as a general-purpose file format that can be handled by spreadsheet software such as Excel.
With the above program, CSV files saved in Excel can be read by your own program.
Not so easy since CSVs saved in Excel tend to be complex...
There is a fscanf function similar to the familiar scanf function.
Its usage is the same as that of the scanf function, except that a file pointer is specified at the beginning.
The scanf function reads from the keyboard, so it waits for input when executed, but the
The fscanf function reads the text of a file from the beginning.
The following program reads and displays the first number from the test.txt file.
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 results of running this program depend 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 "test.txt" file before execution
100
Execution Result
100
If the %d specifier is used, as in the example above, non-numeric text is ignored.
If the contents of the test.txt file were as follows, the execution result would be as follows
Contents of "test.txt" file before execution
test100
Execution Result
100
The entire string can be read by using the %s specifier used for string input.
However, if spaces or other characters are included, only that much will be read.
Contents of "test.txt" file before execution
test100
Execution Result
test100
You can also use a comma (,) to separate multiple numbers in a row.
It is also possible to read multiple variables.
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 "test.txt" file before execution
23,56
Execution Result
i=23 : j=56
A file of numbers and strings separated by commas (,) like this is called a CSV format.
It is known as a general-purpose file format that can be handled by spreadsheet software such as Excel.
With the above program, CSV files saved in Excel can be read by your own program.
Not so easy since CSVs saved in Excel tend to be complex...
About this Site
The C language (bitter C), which is learned by suffering, is
This is the definitive C language introductory site.
It systematically explains the basic functions of the C language and
It is as complete as or better than any book on the market.