当前位置:网站首页>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
边栏推荐
- Will the memory of ParticleSystem be affected by maxparticles
- Sequence sorting of basic exercises of test questions
- Push technology practice | master these two tuning skills to speed up tidb performance a thousand times!
- Logical operator, displacement operator
- Rearrangement of tag number of cadence OrCAD components and sequence number of schematic page
- The automatic control system of pump station has powerful functions and diverse application scenarios
- The difference between lambda expressions and anonymous inner classes
- [leetcode daily question] a single element in an ordered array
- What is the student party's Bluetooth headset recommendation? Student party easy to use Bluetooth headset recommended
- Pesticide synergist - current market situation and future development trend
猜你喜欢
Infiltration learning diary day19
Bacteriostatic circle scanning correction template
Audio resource settings for U3D resource management
Openbionics exoskeleton project introduction | bciduino community finishing
Learn these super practical Google browser skills, girls casually flirt
Use classname to modify style properties
Huawei rip and BFD linkage
C import Xls data method summary II (save the uploaded file to the DataTable instance object)
Conditional test, if, case conditional test statements of shell script
Idea if a class cannot be found, it will be red
随机推荐
Trading software programming
Bacteriostatic circle scanning correction template
Life cycle of instance variables, static variables and local variables
Override and virtual of classes in C #
Hunan University | robust Multi-Agent Reinforcement Learning in noisy environment
Description of setting items of Jerry [chapter]
SRCNN:Learning a Deep Convolutional Network for Image Super-Resolution
Hamburg University of Technology (tuhh) | intelligent problem solving as integrated hierarchical reinforcement learning
Neo4j learning notes
Setting function of Jerry's watch management device [chapter]
G3 boiler water treatment registration examination and G3 boiler water treatment theory examination in 2022
Force buckle day32
[turn] solve the problem of "RSA public key not find" appearing in Navicat premium 15 registration
2020-12-02 SSM advanced integration Shang Silicon Valley
Learn these super practical Google browser skills, girls casually flirt
Related configuration commands of Huawei rip
Basic editing specifications and variables of shell script
Conditional test, if, case conditional test statements of shell script
Idea if a class cannot be found, it will be red
1189. Maximum number of "balloons"