当前位置:网站首页>[C language series] - detailed explanation of file operation (Part 1)
[C language series] - detailed explanation of file operation (Part 1)
2022-07-29 05:36:00 【Gancheng なつき】
꧁ Hello, everybody ! It is a great honor to have your visit , Let's have a long way to go in programming !꧂
* Blog column :【C All living things 】*
Introduction to this article : Detailed introduction C File operation part in language !
Get to know the author : Aspire to be a great programmer , Xiaobai, who is currently a sophomore in College .
Inspirational terms : The tediousness of programming , Let's study together and become interesting !
Text begins
Catalog
Sequential reading and writing of files
Why use files ?
We know that data is stored in memory , When the program exits , Data naturally does not exist , To achieve data persistence , It is necessary to store the data in disk files or databases .
Using files, we can store data directly on the hard disk of the computer , Data persistence .
What is a document ?
A file on disk is a file .
But in programming , There are two kinds of documents :1. Program files 2. Data files ( Classify from the perspective of file function ).
* Program files
Source program files ( The suffix is .c)
Target file (windows Environment suffix is .obj)
Executable program (windows Environment suffix is .exe)
* Data files
The content of the file is not necessarily a program , It's the data that the program reads and writes when it runs , For example, the file from which the program needs to read data or the file of output content .
* file name
A file must have a unique file id , So that users can identify and reference .
The filename contains 3 part : File path + File name trunk ++ file extension
for example : Code E:\C Advanced language \c-language-advanced-code\test_7_24\test.c
For convenience , The file ID is often referred to as the file name
The file pointer
Buffer file system , The key concept is “ File type pointer ”, abbreviation “ The file pointer ”.
Each used file has a corresponding file information area in memory , Used to store relevant information of files ( Such as the name of the document , The status of the file and the current location of the file ). This information is stored in a structure variable , The structure type is system declared , named FILE.
for example : stay VS2022 In the header file stdio.h There are the following file type declarations in :

#ifndef _FILE_DEFINED
#define _FILE_DEFINED
typedef struct _iobuf
{
void* _Placeholder;
} FILE;
#endifBut as the VS The continuous upgrading of this compiler ,FILE The content contained in the type is more and more simplified , But they are similar .
Every time you open a file , The system will automatically create a FILE Structural variables , And fill in the information , Users don't have to care about details .
It's usually through a FILE To maintain this FILE Structural variables , This is more convenient to use .
Let's create a FILE* Pointer variable for :
FILE* pf;// File pointer variable Definition pf It's a point FILE Pointer variable of type data . You can make pf Point to the file information area of a file ( It's a structure ). The file can be accessed through the information in the file information area . in other words , Through the file pointer variable, you can find the file associated with it .
such as :

Opening and closing of files
The file should be opened before reading and writing , The file should be closed after use .
In programming , While opening the file , Will return to one FILE* A pointer variable to the file , It is also equivalent to establishing the relationship between pointer and file .
ANSIC( standard C) To prescribe the use of fopen Function to open a file ,fclose To close the file .
// Open file
FILE* fopen(const char* filename, const char* mode);//( file name , Open method )
// Close file
int fclose(FILE* stream);// File pointer variable name What are the opening methods ? Look at these :
| Meaning of document use | meaning | If the specified file does not exist |
| “r”( read-only ) | To enter data , Open an existing text file | error |
“w”( Just write ) | To output data , Open a text file | Create a new file |
| “a”( Additional ) | Add data to the end of the text file | Create a new file |
| “rb”( read-only ) | To enter data , Open a binary file | error |
| “wb”( Just write ) | To output data , Open a binary file | Create a new file |
| “ab”( Additional ) | Add data to the end of a binary file | error |
| “r+”( Reading and writing ) | For reading and writing , Open a text file | error |
| “w+”( Reading and writing ) | For reading and writing , Create a text file | Create a new file |
| “a+”( Reading and writing ) | Open a file , Read and write at the end of the file | Create a new file |
| “rb+”( Reading and writing ) | Open a binary file for reading and writing | error |
| “wb+”( Reading and writing ) | For reading and writing , Create a new binary file | Create a new file |
| “ab+”( Reading and writing ) | Open a binary file , Read and write at the end of the file | Create a new file |
Let's write an example code :
#include<stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "w");// Open in writing
if (pf == NULL)
{
ferror("File Fail");// Print error messages
return 1;// Erroneous return
}
// Read and write files
// ......
// Close file
fclose(pf);
pf = NULL;
return 0;
}Sequential reading and writing of files
| function | Function name | Apply to |
| Character input function | fgetc | All input streams |
| Character output function | fputc | All output streams |
| Text line input function | fgets | All input streams |
| Text line output function | fputs | All output streams |
| Format input function | fscanf | All input streams |
| Format output function | fprintf | All output streams |
| Binary input | fread | file |
| Binary output | fwrite | file |
* Input and output
* Output and input
What is input ? What is output ? Enter where , Where does the output go ? I believe many Lao tie will be confused , It doesn't matter. , Let's take a look at a picture , I understand. .

good , At a glance , good , Next, we will explain the various functions of these functions !
* fputc
Let's first look at the function of this function :

Function function instance 1:
#include<stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
ferror("fopen fail");
return 1;
}
// Output the file
fputc('c', pf);
// Close file
fclose(pf);
pf = NULL;
return 0;
}Run the output results :

We can see that this character is successfully written into the file .
* fgetc

Function function instance 2:
#include<stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
ferror("fopen fail");
return 1;
}
// Input the file
char c = fgetc(pf);
printf("%c\n", c);
// Close file
fclose(pf);
pf = NULL;
return 0;
}Run the output results :

Print out the characters in the file on the screen .
* fgets And fputs
I have not explained these two functions much here , They just changed the characters to be able to input and output strings , The key points are the following functions .
* fprintf
Let's first look at the function of this function :

Function function instance code 3:
// Specify the format output function
#include<stdio.h>
struct S
{
char name[10];
int age;
float score;
};
int main()
{
struct S s = { "tangcheng",20,99.9f };
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
//fprintf
fprintf(pf, "%s %d %f", s.name, s.age, s.score);
// Close file
fclose(pf);
pf = NULL;
return 0;
}Run the output results :

Format one ( It's the structure ) The data of is output to the file .
* fscanf
First look at the function :

Function function code example 4:
#include<stdio.h>
struct S
{
char name[10];
int age;
float score;
};
int main()
{
struct S s = { 0 };
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
//fscanf
fscanf(pf, "%s %d %f", s.name, &(s.age), &(s.score));
// Print
fprintf(stdout,"%s %d %f\n", s.name, s.age, s.score);//stdout Is the standard output stream - The screen
// Close file
fclose(pf);
pf = NULL;
return 0;
}Running results ( Input the formatted data in the file into the screen ):

* fwrite
The function of this function :
function
fwrite // Where to put it How many bytes How many? The file pointer
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );Write block of data to stream
The sample code 5:
#include<stdio.h>
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s = { "zhangsan",20,50.5f };
// Open file Output to file in binary mode
FILE* pf = fopen("test.txt", "wb");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Write in binary
fwrite(&s, sizeof(struct S), 1, pf);
// Close file
fclose(pf);
pf = NULL;
return 0;
}The result of running :

Is it a little hard to understand , Because this is binary data , We don't need to understand , The compiler can understand it . How to enter it on the screen , Don't worry. , Let's introduce fread This function .
* fread
The functionality :
function
fread // Where to put it How many bytes Number The file pointer
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );Read block of data from stream
The sample code 6:
#include<stdio.h>
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s = { 0 };
// Open file
FILE* pf = fopen("test.txt", "rb");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Read in binary
fread(&s, sizeof(struct S), 1, pf);
// A print
printf("%s %d %f", s.name, s.age, s.score);
// Close file
fclose(pf);
pf = NULL;
return 0;
}Running results :

??? It's not a binary file , It shows that the compiler automatically recognizes that binary data is converted into formatted data that we can understand .
Conclusion
Family , There are too many details about file operation , It can only be divided into ( On ) and ( Next ) There are two parts to write !!!

边栏推荐
- Day 1
- 携手数字人、数字空间、XR平台,阿里云与伙伴共同建设“新视界”
- 【C语言系列】—深度解剖数据在内存中的存储(一) 暑假开篇
- [event preview] cloud digital factory and digital transformation and innovation forum for small and medium-sized enterprises
- Clickhouse learning (V) cluster operation
- Pyqt5: Chapter 1, Section 1: creating a user interface using QT components - Introduction
- [C language series] - realize the exchange of two numbers without creating the third variable
- 弹性盒子相关知识
- 力扣994:腐烂的橘子(BFS)
- C language first level pointer
猜你喜欢

携手数字人、数字空间、XR平台,阿里云与伙伴共同建设“新视界”

抢先预约 | 阿里云无影云应用线上发布会预约开启

力扣994:腐烂的橘子(BFS)

【C语言系列】— 一道递归小题目

阿里云张新涛:异构计算为数字经济提供澎湃动力

Flask 报错 RuntimeError: The session is unavailable because no secret key was set.

ClickHouse学习(五)集群操作

Selenium实战案例之爬取js加密数据

Three handshakes and four waves for the interview summary

B - identify floating point constant problems
随机推荐
题解:在一个排序数组中查找元素第一个和最后一个的位置 (个人笔记)
H5语义化标签
Cryengine Technology
C language n queen problem
B - identify floating point constant problems
牛客网编程题—【WY22 Fibonacci数列】和【替换空格】详解
Cmu15-213 malloc lab experiment record
Abstract classes and interfaces
PyQt5:第一章第1节:使用Qt组件创建一个用户界面-介绍
Longest string without duplicate characters
刷题狂魔—LeetCode之剑指offer58 - II. 左旋转字符串 详解
【C语言系列】— 不创造第三个变量,实现两个数的交换
利用Poi-tl在word模板表格单元格内一次插入多张图片和多行单元格相同数据自动合并的功能组件
Do students in the science class really understand the future career planning?
Camunda 1、Camunda工作流-介绍
vim编辑器使用
Day 1
167. Sum of two numbers II - enter an ordered array
VIM editor use
弹性盒子flex