当前位置:网站首页>[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;
#endif
But 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 !!!
边栏推荐
- Using POI TL to insert multiple pictures and the same data of multiple rows of cells into the table cells of word template at one time, it is a functional component for automatic merging
- C language one-dimensional array
- ClickHouse学习(七)表查询优化
- rem与px与em异同点
- Common shortcut keys for Ad
- C language first level pointer
- TXT 纯文本操作
- [event preview] cloud digital factory and digital transformation and innovation forum for small and medium-sized enterprises
- link与@import导入外部样式的区别
- 相对定位和绝对定位
猜你喜欢
eggjs 创建应用知识点
Global components component registration
ClickHouse学习(二)ClickHouse单机安装
ClickHouse学习(十)监控运行指标
携手数字人、数字空间、XR平台,阿里云与伙伴共同建设“新视界”
【C语言系列】— 字符串+部分转义字符详解+注释小技巧
Alibaba cloud architect details nine trends in the game industry
【C语言系列】—深度解剖数据在内存中的存储(二)-浮点型
Occt learning 003 - MFC single document project
Cmu15-213 malloc lab experiment record
随机推荐
抽象类与接口
【C语言系列】— 一道递归小题目
B - identify floating point constant problems
VIM editor use
vim编辑器使用
uniapp之常用提示弹框
指针
力扣994:腐烂的橘子(BFS)
Clickhouse learning (VIII) materialized view
科班同学真的了解未来的职业规划吗?
Day 2
167. Sum of two numbers II - enter an ordered array
Flask 报错 RuntimeError: The session is unavailable because no secret key was set.
Preemptive appointment | Alibaba cloud shadowless cloud application online conference appointment opens
Occt learning 003 - MFC single document project
Camunda 1、Camunda工作流-介绍
365 day challenge leetcode 1000 questions - day 040 design jump table + avoid flooding + find the latest grouping with size M + color ball with reduced sales value
ANSI C类型限定符
ANSI C type qualifier
Clickhouse learning (IV) SQL operation