当前位置:网站首页>17. File i/o buffer
17. File i/o buffer
2022-07-04 01:59:00 【666QAQ】
Simply put, system calls and stdio I/O Function in When working with disk files Data will be buffered .
Because the disk is too slow to read and write , And memory is faster .
Kernel buffer cache
The first is the system call , Such as write()
and read()
, Disk access will not be initiated directly when operating disk files , But in User space buffer And Kernel buffer cache Assign data between .
The kernel will Kernel buffer cache The data in is exchanged with the disk .
Control kernel buffer
Too hard, too hard , It doesn't work ... Temporarily abandon ...
stdio buffer
and stdio
The library also maintains its own buffer ,stdio buffer By system call (write()
、read()
) And Kernel buffer cache Data exchange between .
control stdio Buffering of streams
fflush()
Use fflush()
You can force stdio
The data in the output stream is refreshed to Kernel buffer .
#include <stdio.h>
int fflush(FILE *stream);
Returns 0 on success, EOF on error
- If parameter
stream
by NULL, befflush()
Will refresh allstdio
buffer . - Also can be
fflush()
For input stream , This will discard the buffered data . - When the corresponding flow is closed , Will automatically refresh its
stdio
buffer . - Include
glibc
Many, including libraries C Function library implementation , ifstdin
andstdout
Point to a terminal , So whenever fromstdin
When reading input in , Will be implicitly called oncefflush(stdout)
function . This will refresh the writestdout
Any tips for , But not including the terminating newline .( But it's not SUSv3 or C99 Stipulated .)
setvbuf()
#include <stdio.h>
int setvbuf(FILE *stream, char *buf, int mode, size_t size);
Returns 0 on success, or nonzero on error
Parameters
stream
Identify the buffer of the file stream to be modified , After opening the stream , You must call any otherstdio
Call... Before the functionsetvbuf()
.setvbuf()
Will affect all subsequentstdio
operation .
Parametersbuf
andsize
For the buffer to be usedIf parameters
buf
Not for NULL, Then it pointssize
Size of memory block asstream
The buffer . This buffer should be allocated on the heap .if
buf
by NULL, thatstdio
Automatically forstream
Allocate a buffer ( Unless you choose unbuffered I/O),SUSv3 It is allowed but not mandatory for the library to implementsize
To determine the size of its buffer .glibc
The implementation will ignoresize
Parameters .mode
Parameters- _IONBF
incorrect I/O Buffering . Everystdio
The library function immediately callswrite()
perhapsread()
, And ignorebuf
andsize
Parameters , You can specify two parameters asNULL
and0
..stderr
It belongs to this type by default , So that the error can be output immediately . - _IOLBF
Use line buffering I/O. The stream that refers to the terminal device belongs to this type by default . For output streams , Output a line break ( Unless the buffer is full ) Data will be buffered before . For input streams , Read one line of data at a time . - _IOFBF
Fully buffered I/O. Single reading 、 Writing data ( adoptwrite()
perhapsread()
system call ) Is the same size as the buffer . The stream that refers to disk adopts this mode by default .
- _IONBF
Examples of use :
#define BUF_SZIE 1024
static char buf[BUF_SIZE];
if(setvbuf(stdout, buf, _IOFBF, BUF_SIZE) != 0)
{
printf("setvbuf");
exit(EXIT_FAILURE);
}
setbuf()
#include <stdio.h>
void setbuf(FILE *stream, char *buf);
setbuf(fp, buf)
Except that the call does not return the result of the function , Equivalent to :setvbuf(fp, buf, (buf != NULL)? _IOFBF : _IONBF, BUFSIZ
- The parameter
buf
Designated asNULL
No buffer , Or point to the assigned by the callerBUFSIZ
Byte size buffer .(BUFSIZ
Defined in<stdio.h>
Header file .glibc
The library implementation defines this constant as a typical value 8192).
setbuffer()
#define _BSD_SOURCE
#include <stdio.h>
void setbuffer(FILE *stream, char *buf, size_t size);
setbuffer()
The function is similar to setbuf()
function , But the caller is allowed to specify buf
Size of buffer .
Yes setbuffer(fp, buf, size)
But with the following calls :setvbuf(fp, (buf != NULL) ? _IOFBF : _IONBF, size)
Mix library functions and system calls for file I/O
Execute on the same file I/O In operation , You can also combine system calls with standards C Mixed use of language function libraries . This needs to be fileno()
and fdopen()
function .
#include <stdio.h>
int fileno(FILE *stream);
Returns file descriptor on success, or -1 on error
FILE *fdopen(int fd, const char *mode);
Returns (new)file pointer on success, or NULL on error
- Given a ( file ) flow ,
fileno()
Function will return the corresponding file descriptor ( namelystdio
The file descriptor that the library has opened on this stream ). Then you can use it in places such asread()
、write()
、dup()
、fcntl()
And so on. I/O This file descriptor is normally used in system calls . fdopen()
Function andfileno()
The function does the opposite . Given a file descriptor , This function will create a file that uses this descriptor I/O Corresponding flow of .mode
Parameters andfopen()
Functionmode
Parameters have the same meaning . for example ,w For writing ,a To add . If this parameter is the same as the file descriptor fd The access mode of is inconsistent , On the other handfdopen()
Call to will fail .
fdopen()
Especially useful for unconventional file descriptors , Such as socket 、 The Conduit , Creation time , System calls always return file descriptors . In order to use in this series of document types stdio
Library function , You have to use fdopen()
Function to create the corresponding file stream .
Mixed use , Keep in mind :I/O The system call will directly pass the data to Kernel buffer cache , and stdio
The library function waits until the stream buffer in user space is full , Call again write()
Pass it on to Kernel buffer cache .
for example :
printf("123\n");
write(STDOUT_FILENO, "456\n", 4);
The result is :
456
123
have access to fflush()
To avoid this problem :
printf("123\n");
fflush(stdout);
write(STDOUT_FILENO, "456\n", 4);
Execution results :
123
456
边栏推荐
- Hunan University | robust Multi-Agent Reinforcement Learning in noisy environment
- G3 boiler water treatment registration examination and G3 boiler water treatment theory examination in 2022
- IPv6 experiment
- [turn] solve the problem of "RSA public key not find" appearing in Navicat premium 15 registration
- Example 072 calculation of salary it is known that the base salary of an employee of a company is 500 yuan. The amount of software sold by the employee and the Commission method are as follows: Sales
- Valentine's Day - 9 jigsaw puzzles with deep love in wechat circle of friends
- Basic editing specifications and variables of shell script
- How programmers find girlfriends through blind dates
- Pytoch residual network RESNET
- In yolov5, denselayer is used to replace focus, and the FPN structure is changed to bi FPN
猜你喜欢
On Valentine's day, I code a programmer's exclusive Bing Dwen Dwen (including the source code for free)
The boss said: whoever wants to use double to define the amount of goods, just pack up and go
What are the advantages and disadvantages of data center agents?
Remember another interview trip to Ali, which ends on three sides
51 MCU external interrupt
Should enterprises start building progressive web applications?
Small program graduation project based on wechat video broadcast small program graduation project opening report function reference
Introduction to superresolution
ES6 deletes an attribute in all array objects through map, deconstruction and extension operators
Basic editing specifications and variables of shell script
随机推荐
Containerization technology stack
Special copy UML notes
Do you know the eight signs of a team becoming agile?
1189. Maximum number of "balloons"
Question d: Haffman coding
Should enterprises start building progressive web applications?
String & memory function (detailed explanation)
Openbionics robot project introduction | bciduino community finishing
Huawei cloud micro certification Huawei cloud computing service practice has been stable
Idea if a class cannot be found, it will be red
The contact data on Jerry's management device supports reading and updating operations [articles]
2022 R2 mobile pressure vessel filling certificate examination and R2 mobile pressure vessel filling simulation examination questions
Software product download collection
The reasons why QT fails to connect to the database and common solutions
MPLS③
Override and virtual of classes in C #
Mobile phone battery - current market situation and future development trend
Make drop-down menu
Three layer switching ②
Ka! Why does the seat belt suddenly fail to pull? After reading these pictures, I can't stop wearing them