当前位置:网站首页>[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 !!!

边栏推荐
- C语言 一级指针
- 刷题狂魔—LeetCode之剑指offer58 - II. 左旋转字符串 详解
- 【C语言系列】—文件操作详解(上)
- 第一周总结
- Basic use of redis
- Cryengine3 debugging shader method
- PyQt5:第一章第1节:使用Qt组件创建一个用户界面-介绍
- Together with digital people, digital space and XR platform, Alibaba cloud and its partners jointly build a "new vision"
- Occt learning 003 - MFC single document project
- Summary of the first week
猜你喜欢

【剑指offer】— 详解库函数atoi以及模拟实现atoi函数

【C语言系列】— 不创造第三个变量,实现两个数的交换

阿里云联合鼎捷软件发布云上数字工厂解决方案,实现云MES系统本地化部署

ClickHouse学习(九)clickhouse整合mysql

AR虚拟增强与现实

Pyqt5: Chapter 1, Section 1: creating a user interface using QT components - Introduction

C language one-dimensional array

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

ClickHouse学习(八)物化视图

On Paradigm
随机推荐
Clickhouse learning (V) cluster operation
Best practices for elastic computing in the game industry
个人学习笔记
365 day challenge leetcode 1000 questions - day 039 full binary tree inserter + find peak II + snapshot array
Abstract classes and interfaces
Summary of the first week
Realize simple database query (incomplete)
Longest string without duplicate characters
数据库操作 Day 6
【无标题】
Day 2
paddle. Fluid constant calculation error 'nonetype' object has no attribute 'get_ fetch_ list‘
shell基本操作(上)
Thrift安装手册
redis的基本使用
数组学习之入门简单题 两数之和
Differences between texture2d and texture2dproj under webgl1.0
Global components component registration
uniapp之常用提示弹框
利用Poi-tl在word模板表格单元格内一次插入多张图片和多行单元格相同数据自动合并的功能组件