当前位置:网站首页>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
边栏推荐
- Human resource management online assignment
- String & memory function (detailed explanation)
- TP5 automatic registration hook mechanism hook extension, with a complete case
- Trading software programming
- What are the main investment products of bond funds and what are they
- 2022 electrician (elementary) examination question bank and electrician (elementary) simulation examination question bank
- Intel's new GPU patent shows that its graphics card products will use MCM Packaging Technology
- 1189. Maximum number of "balloons"
- Openbionics exoskeleton project introduction | bciduino community finishing
- Bacteriostatic circle scanning correction template
猜你喜欢
Introduction to graphics: graphic painting (I)
LeetCode 168. Detailed explanation of Excel list name
Force buckle day32
Introduction to superresolution
Life cycle of instance variables, static variables and local variables
Yyds dry goods inventory it's not easy to say I love you | use the minimum web API to upload files
Chapter 3.4: starrocks data import - Flink connector and CDC second level data synchronization
ES6 deletes an attribute in all array objects through map, deconstruction and extension operators
Applet graduation project is based on wechat classroom laboratory reservation applet graduation project opening report function reference
Install the pit that the electron has stepped on
随机推荐
Valentine's Day - 9 jigsaw puzzles with deep love in wechat circle of friends
Jerry's modification setting status [chapter]
Portable two-way radio equipment - current market situation and future development trend
Prose article appreciation - the rain in the warm country has never changed into cold, hard and brilliant flowers. Knowledgeable people think he is monotonous, and he thinks he is unlucky, doesn't he?
TP5 automatic registration hook mechanism hook extension, with a complete case
Solution to the problem that jsp language cannot be recognized in idea
Difference between value and placeholder
How to delete MySQL components using xshell7?
MySQL deadly serial question 2 -- are you familiar with MySQL index?
Conditional statements of shell programming
[turn] solve the problem of "RSA public key not find" appearing in Navicat premium 15 registration
Meta metauniverse female safety problems occur frequently, how to solve the relevant problems in the metauniverse?
The reasons why QT fails to connect to the database and common solutions
How programmers find girlfriends through blind dates
Cancer biopsy instruments and kits - market status and future development trends
[leetcode daily question] a single element in an ordered array
Ceramic metal crowns - current market situation and future development trend
Jerry's update contact [article]
What is the student party's Bluetooth headset recommendation? Student party easy to use Bluetooth headset recommended
Customize redistemplate tool class