《unix环境高级编程》是这么说的:

标准IO流操作读写普通文件是使用全缓冲的,默认缓冲区长度是该文件系统优先选用的IO长度(从stat结构得到的st_blksize值)

//读取st_blksize的例子:

int main(int argc, char* argv[])
{
    if(argc!=2)
    {
        printf("2 argment\n");
        return 0;
    }

    struct stat buf;
    stat(argv[1], &buf);
    printf("st_blksize=%d,st_blocks=%d\n", (int)buf.st_blksize, (int)buf.st_blocks);
    
    return 0;
}

setvbuf 用法:
语法: #include <stdio.h>

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, 表示无缓存

程序例:


/* setvbuf example */
#include <stdio.h>

char sBuf[1024];

int main ()
{
FILE *pFile;
pFile=fopen ("myfile.txt","w");
setvbuf ( pFile , sBuf, _IOFBF , 1024 );

// File operations here
fclose (pFile);
return 0;
}
在这个例子中,每次写1024字节,所以只有缓冲区满了(有1024字节),才往文件写入数据,可以减少IO次数

posted on 2011-07-18 11:58  眼里的圈圈  阅读(8661)  评论(0编辑  收藏  举报