setbuf与setvbuf函数,C语言setbuf与setvbuf函数详解

  • 内容
  • 评论
  • 相关

在讨论 setvbuf 与 setbuf 函数之前,先来看如下一段示例代码:

int main(void)
{
    FILE* fp=NULL;
    int fd;
    const char *f1="testfprintf.log";
    const char *f2="testwrite.log";
    fp = fopen(f1, "wb");
    if(fp == NULL)
    {
        return -1;
    }
    fd = open(f2, O_WRONLY|O_CREAT|O_EXCL, 0666);
    if(fd < 0)
    {
        return -1;
    }
    while(1)
    {
        fprintf(fp, "fprintf------|\n");
        write(fd, "write|\n", sizeof("write|\n"));
        sleep(1);
    }
    return 0;
}

在上面的示例代码中,使用 fprintf 函数对文件 testfprintf.log 执行写入操作,使用 write 函数对文件 testwrite.log 执行写入操作。这里需要注意的是,因为 fprintf 函数会缓冲 4096 字节的数据,只有当达到这么多字节的数据时才会进行实际的磁盘写入。

因此,运行上面的示例程序,然后实时查看 testfprintf.log 文件与 testwrite.log 文件,会发现 testfprintf.log 文件不会被实时写入,只有当写入的数据的大小为 4096 字节的倍数的时候才会被写入;而 write 函数则不同,因为它不进行任何缓冲(直接写入磁盘),所以文件 testwrite.log 不断有数据写入,运行结果如图 1 所示。



图 1 示例代码的运行结果

本文标题:setbuf与setvbuf函数,C语言setbuf与setvbuf函数详解

本文地址:https://www.hosteonscn.com/2805.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注