当前位置:网站首页>In depth analysis - file operation
In depth analysis - file operation
2022-07-27 22:50:00 【Shilipo Xiaobai】
List of articles
Depth analysis : data
Depth analysis : recursive
Depth analysis : Structure
Depth analysis : Dynamic memory management
Depth analysis : File operations
List of articles
- List of articles
- Preface
- One 、 Example questions : Information storage of address book
- Two 、 File storage
- 3、 ... and 、 Opening and closing of files
- Four 、 Sequential reading and writing of files
- 5、 ... and 、 Random reading and writing of documents and end determination
- summary
Preface
Files are a very important part of today's computer system . Files are used to store programs 、 file 、 data 、 graphics 、 Photo 、 video 、 letter 、 Tables and many other kinds of information . As a programmer , Must be able to write programs to create files and read and write data from files . This article will introduce relevant contents .
One 、 Example questions : Information storage of address book
1. Address book requirements
The address book needs a space to store information , It can be accessed at any time when necessary
Our commonly used address book can store information after use , When we need to retrieve information again , The contents still exist , At this time, we need a file to store relevant information . 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 output content file .
Two 、 File storage
1. standard I/O
I/O Two levels of ( There are two levels of handling file access ) :
- Bottom I/O( low-level I/O ): Use the basics provided by the operating system I/O .
- Standard advanced I/O( standard high-level I/O ): Use C Library standard package stdio.h Header file definition .
standard I/O The advantages of :
- standard I/O There are many specialized functions that simplify dealing with different I/O The problem of .
- Better portability .
- Input and output are buffered . in other words , Transfer one large piece of information at a time instead of one byte of information ( Usually at least 512 byte ).
- Have higher data transmission rate .
2. Document classification
In programming , There are two kinds of documents we usually talk about : Program files 、 Data files
Program files : Include source 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 output content file .
3. file type
According to the organization of data , Data files are called text files or binary files
text file : If it's required to use ASCII In the form of code , You need to convert before storing . With ASCII A file stored in the form of characters is a text file .
Xiaoming man 11111 XXX university 
Binary : Data is stored in memory in binary form , If the output without conversion is to external memory , Binary files .
4. File buffer
ANSIC The standard is “ Buffer file system ” Processing of data files , The so-called buffer file system means that the system automatically opens up a block in memory for each file being used in the program “ File buffer ”. Data output from memory to disk is first sent to a buffer in memory , After the buffer is filled, it is sent to the disk together . If you read data from disk to computer , Then read the data from the disk file and input it into the memory buffer ( Fill the buffer ), And then send the data from the buffer to the program data area one by one ( Program variables, etc ). The size of the buffer depends on C The compiler system decides .

5. The file pointer
Buffer file system , The key concept is “ File type pointer ”, abbreviation “ The file pointer ”
FILE *pf;// File pointer variable
Each used file has a corresponding file information area in memory , It is used to store information about files ( Such as the name of the document , Document status and The current location of the file, etc ). This information is stored in a structure variable . The structure type is system declared , The name FILE.
Different C Compiler FILE Types don't contain exactly the same content , But it's the same . Every time you open a file , The system will automatically create a FILE Structural variables , And fill in the information , The user does not have to turn off Heart details .
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 structural variable ). Through this article The information in the file information area can access the file . in other words , Through the file pointer variable, you can find the file associated with it .
3、 ... and 、 Opening and closing of files
1. File switch function
- fopen
Call structure
FILE *fopen(" file name . suffix ", " Open mode ");
Return a pointer , You need to determine whether it is a null pointer
- fclose
Call structure
int fclose( File address );
Closing successfully returns 0, Otherwise return to EOF(-1)
Invoke the sample
FILE *P_File = fopen(" file name . suffix ", " Open mode ");
if (P_File == NULL) {
perror(" fail to open file :");
}
fclose(P_File);
2. How to open the file
| How files are used | 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 | error |
| “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 , Suggest a new 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 |
Four 、 Sequential reading and writing of files
1. Character input and output (fputc & fgetc)
- fputc
Call structure
int fputc(int , FILE *stream);
Write data to file ( Write from the end )
Invoke the sample
fputc('1', P_File);
fputc('2', P_File);
fputc('3', P_File);
- fgetc
Call structure
int fgetc(FILE *stream);
Read data to file ( Read in sequence from the beginning , Read once and walk backward one space )
- After reading, return to EOF
- Normal reading returns ASCII Code value
Invoke the sample
int ret = fgetc(P_File);
printf("%c", ret);
2. Text line I / O function (fputs & fgets)
- fputs
Call structure
int fputs(const char *str, File *stream);
Write data to file ( Write from the end )
Invoke the sample
fputs("abcdef\n", P_File);
fputs("123456\n", P_File);
- fgets
Call structure
char *fgets(char *str, int n, FILE *stream)
The number of reads n Include
'/0'The location of , So read at most n - 1 individual
Invoke the sample
fgets(arr, 5, P_File);
printf("%s\n", arr);
fgets(arr, 20, P_File);
printf("%s\n", arr);
3. Format input and output functions (fprintf & fscanf)
- fprintf
Call structure
int fprintf(File *stream, Back with printf Agreement );
Write data to file ( Write from the end )
Invoke the sample
fprintf(P_File, "%s\n", "hello world!");
- fscanf
Call structure
int fscanf(File *stream, Back with scanf Agreement );
Read ( From the beginning )
Invoke the sample
fscanf(P_File, "%s", arr);
printf("%s\n", arr);
4. Binary I / O functions (fwrite & fread)
- fwrite
Call structure
int fwrite( The address of the element to be written , The size of each element , Number of elements , File *stream);
Write... In binary ( The string is written in binary and text, and the result is the same )
Invoke the sample
fwrite(arr, sizeof(char), 20, P_File);
- fread
Call structure
int fread( The address of the element to be read , The size of each element , Number of elements , File *stream);
Return the number of read complete elements , If the number read < The actual number of readings , Is the last read
Invoke the sample
fread(arr, sizeof(char), 20, P_File);
5、 ... and 、 Random reading and writing of documents and end determination
1. Random reading and writing of documents
- fseek
Call structure
int fseek(" file ", Offset , The starting position of the offset );
Determine the writing position
- SEEK_CUR - The current position
- SEEK_SET - Starting position
- SEEK_END - Ending position ( When pointing to the end , The offset can only be negative )
- fwind
Call structure
int fwind(" file ");
Return the file pointer to the starting position
2. Determination of the end of the document
- feof
Call structure
int feof( File address );
Is to judge the end of reading failure , Or the end of the file
- Whether the reading of text file is finished , Determine whether the return value is EOF, Or is it NULL etc. . Each function has a specific end flag .
- Judgment of reading end of binary file , Judge whether the return value is less than the actual number to be read .
summary
For most programs , Relevant operations of documents are essential . standard I/O The package automatically creates input and output buffers to speed up data transmission . A variety of input and output methods make the program more flexible and convenient , Greatly improve the efficiency of the program , At the same time, it also has good portability .
边栏推荐
- `What is the difference between SSH -y` (trusted X11 forwarding) and 'SSH -x` (untrusted X11 forwarding)?
- 深度剖析 —— 文件操作
- QT common operation collection
- Kubernetes二进制部署——理论部分
- Chrome realizes automated testing: recording and playback web page actions
- The wave of smart home is coming, how to make machines understand the world [there is information at the end]
- The follow-up is coming. Whether it's OK without reference, let's make it clear to everyone at once!
- Can uniswap integrate sudoswap to open a new prelude to NFT liquidity?
- 2021年福建省职业院校技能大赛(中职组)网络安全竞赛任务书
- Buuctf brushes eleven questions (05)
猜你喜欢

Leetcode383 ransom letter

数据仓库项目从来不是技术项目

What is private traffic?

SparkSQL的UDF及分析案例,220726,,

The follow-up is coming. Whether it's OK without reference, let's make it clear to everyone at once!

七大排序之希尔排序

SQL injection less26a (Boolean blind injection)
![[illustration] shake hands three times and wave hands four times - it's enough to read this article carefully](/img/b1/af520cec44e849e8828a86fc7a2614.png)
[illustration] shake hands three times and wave hands four times - it's enough to read this article carefully

UDF and analysis cases of sparksql, 220726,,

Alibaba Senior Software Testing Engineer recommends testers to learn -- Introduction to security testing
随机推荐
Jeninkins离线部署
In depth understanding of redis master-slave principle
ConvNeXt:A ConvNet for the 2020s——模型简述
Setcontentview details
If there is no reference ground at all, guess if you can control the impedance?
Window localStorage 属性和Location 对象
MediaTek and Samsung launched the world's first 8K TV that supports Wi Fi 6
初中三年回忆录
mmu学习总结
RN search highlight
Leetcode15 -- sum of three numbers
What is the employment prospect of software testing?
Uniswap集成sudoswap,能否拉开NFT流动性新序幕?
联合省选2022复习计划
jstack那些事
Jumpserver learning
2021 Fujian Vocational College skills competition (secondary vocational group) network security competition assignment
2022/3/22考试总结
[NOI2018] 冒泡排序(组合+卡特兰数+dp+树状数组)
Here comes Gree mask! Kn95 mask only costs 5.5 yuan!