当前位置:网站首页>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
streamby NULL, befflush()Will refresh allstdiobuffer . - Also can be
fflush()For input stream , This will discard the buffered data . - When the corresponding flow is closed , Will automatically refresh its
stdiobuffer . - Include
glibcMany, including libraries C Function library implementation , ifstdinandstdoutPoint to a terminal , So whenever fromstdinWhen reading input in , Will be implicitly called oncefflush(stdout)function . This will refresh the writestdoutAny 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
streamIdentify the buffer of the file stream to be modified , After opening the stream , You must call any otherstdioCall... Before the functionsetvbuf().setvbuf()Will affect all subsequentstdiooperation .
ParametersbufandsizeFor the buffer to be usedIf parameters
bufNot for NULL, Then it pointssizeSize of memory block asstreamThe buffer . This buffer should be allocated on the heap .if
bufby NULL, thatstdioAutomatically forstreamAllocate a buffer ( Unless you choose unbuffered I/O),SUSv3 It is allowed but not mandatory for the library to implementsizeTo determine the size of its buffer .glibcThe implementation will ignoresizeParameters .modeParameters- _IONBF
incorrect I/O Buffering . EverystdioThe library function immediately callswrite()perhapsread(), And ignorebufandsizeParameters , You can specify two parameters asNULLand0..stderrIt 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
bufDesignated asNULLNo buffer , Or point to the assigned by the callerBUFSIZByte size buffer .(BUFSIZDefined in<stdio.h>Header file .glibcThe 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 ( namelystdioThe 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 .modeParameters andfopen()FunctionmodeParameters 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
边栏推荐
- Question d: Haffman coding
- [typora installation package] old typera installation package, free version
- C import Xls data method summary III (processing data in datatable)
- Do you know the eight signs of a team becoming agile?
- MySQL statement learning record
- Valentine's Day - 9 jigsaw puzzles with deep love in wechat circle of friends
- 2022 R2 mobile pressure vessel filling certificate examination and R2 mobile pressure vessel filling simulation examination questions
- Conditional test, if, case conditional test statements of shell script
- LeetCode 168. Detailed explanation of Excel list name
- Remember another interview trip to Ali, which ends on three sides
猜你喜欢

TP5 automatic registration hook mechanism hook extension, with a complete case

A fan summed up so many interview questions for you. There is always one you need!

Conditional test, if, case conditional test statements of shell script

MySQL advanced SQL statement (1)

Small program graduation project based on wechat examination small program graduation project opening report function reference

2020-12-02 SSM advanced integration Shang Silicon Valley

Rearrangement of tag number of cadence OrCAD components and sequence number of schematic page

MySQL introduction - functions (various function statistics, exercises, details, tables)

C import Xls data method summary II (save the uploaded file to the DataTable instance object)

The automatic control system of pump station has powerful functions and diverse application scenarios
随机推荐
Experimental animal models - current market situation and future development trend
Huawei rip and BFD linkage
求esp32C3板子連接mssql方法
Pyrethroid pesticide intermediates - market status and future development trend
Customize redistemplate tool class
2022 new examination questions for safety management personnel of hazardous chemical business units and certificate examination for safety management personnel of hazardous chemical business units
Chain ide -- the infrastructure of the metauniverse
Douban scoring applet Part-3
[typora installation package] old typera installation package, free version
Conditional test, if, case conditional test statements of shell script
2022 R2 mobile pressure vessel filling certificate examination and R2 mobile pressure vessel filling simulation examination questions
Applet graduation project based on wechat selection voting applet graduation project opening report function reference
Yyds dry goods inventory it's not easy to say I love you | use the minimum web API to upload files
Small program graduation project based on wechat reservation small program graduation project opening report reference
Pyinstaller packaging py script warning:lib not found and other related issues
Small program graduation design is based on wechat order takeout small program graduation design opening report function reference
Huawei cloud micro certification Huawei cloud computing service practice has been stable
Chapter 3.4: starrocks data import - Flink connector and CDC second level data synchronization
Ceramic metal crowns - current market situation and future development trend
MySQL statement learning record