setvbuf 语法: #include <stdio.h> int setvbuf( FILE *stream, char *buffer, int mode, size_t size );
int setvbuf( FILE *stream, char *buffer, int mode, size_t size );
Parameters stream Pointer to FILE structure.
buffer User-allocated buffer.
mode Mode of buffering.
size Buffer size in bytes. Allowable range: 2 <= size <= INT_MAX (2147483647). Internally, the value supplied for size is rounded down to the nearest multiple of 2.
函数setvbuf()设置用于stream(流)的缓冲区到buffer(缓冲区),其大小为size(大小). mode(方式)可以是:
_IOFBF, 表示完全缓冲 _IOLBF, 表示线缓冲 _IONBF, 表示无缓存
程序例: #include <stdio.h> int main(void) { FILE *input, *output;
char bufr[512];
input = fopen("file.in", "r+b");
output = fopen("file.out", "w");
/* set up input stream for minimal disk access,
using our own character buffer */
if (setvbuf(input, bufr, _IOFBF, 512) != 0)
printf("failed to set up buffer for input file\n"); else printf("buffer set up for input file\n"); /* set up output stream for line buffering using space that will be obtained through an indirect call to malloc */
if (setvbuf(output, NULL, _IOLBF, 132) != 0) printf("failed to set up buffer for output file\n"); else printf("buffer set up for output file\n");
/* perform file I/O here */ /* close files */
fclose(input); fclose(output); return 0; }
/* setvbuf example */ #include <stdio.h>
int main () { FILE *pFile;
pFile=fopen ("myfile.txt","w");
setvbuf ( pFile , NULL , _IOFBF , 1024 );
// File operations here
fclose (pFile);
return 0; } 在这个例子中,每次写1024字节,所以只有缓冲区满了(有1024字节),才往文件写入数据,可以减少IO次数
|