当前位置:网站首页>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
边栏推荐
- Applet graduation project based on wechat selection voting applet graduation project opening report function reference
- It's corrected. There's one missing < /script >, why doesn't the following template come out?
- Small program graduation project based on wechat examination small program graduation project opening report function reference
- [leetcode daily question] a single element in an ordered array
- Feign implements dynamic URL
- LeetCode 168. Detailed explanation of Excel list name
- Maximum entropy model
- LV1 tire pressure monitoring
- Skku| autonomous handover decision of UAV Based on deep reinforcement learning
- Why can't it run (unresolved)
猜你喜欢
[turn] solve the problem of "RSA public key not find" appearing in Navicat premium 15 registration
Hbuilder link Xiaoyao simulator
Do you know the eight signs of a team becoming agile?
LV1 tire pressure monitoring
Use classname to modify style properties
Override and virtual of classes in C #
Infiltration learning diary day19
Yyds dry goods inventory hand-in-hand teach you the development of Tiktok series video batch Downloader
Solution of cursor thickening
IPv6 experiment
随机推荐
Override and virtual of classes in C #
Conditional statements of shell programming
Day05 branch and loop (II)
After listening to the system clear message notification, Jerry informed the device side to delete the message [article]
Make drop-down menu
LV1 previous life archives
MySQL introduction - functions (various function statistics, exercises, details, tables)
Introduction to Tianchi news recommendation: 4 Characteristic Engineering
ThinkPHP uses redis to update database tables
Conditional test, if, case conditional test statements of shell script
Bacteriostatic circle scanning correction template
MPLS③
LeetCode 168. Detailed explanation of Excel list name
Learn these super practical Google browser skills, girls casually flirt
SRCNN:Learning a Deep Convolutional Network for Image Super-Resolution
A. Div. 7
When the watch system of Jerry's is abnormal, it is used to restore the system [chapter]
Sequence sorting of basic exercises of test questions
Small program graduation project based on wechat video broadcast small program graduation project opening report function reference
Gnupg website