C++ fwrite()

fwrite() 原型

size_t fwrite(const void * buffer, size_t size, size_t count, FILE * stream);

fwrite() 函数将指定数量的、每个大小为 size 字节的对象写入到给定的输出流中。

它类似于调用 fputc() size 次来写入每个对象。根据写入的字符数,文件位置指示器会被增加。如果读取文件时发生任何错误,文件位置指示器的结果值将是不确定的。

  • 如果对象不是可以轻松复制的,则行为是未定义的。
  • 如果 size 或 count 为零,则调用 fwrite 将返回零,并且不执行任何其他操作。

它定义在 <cstdio> 头文件中。

fwrite() 参数

  • buffer: 要写入内容的内存块的 指针
  • size: 每个对象的大小(以字节为单位)。
  • count: 要读取的对象数量。
  • stream: 要将数据写入的文件流。

fwrite() 返回值

fwrite() 函数返回成功读取的对象数量。如果发生错误,返回值可能小于 count。

示例 1:fwrite() 函数如何工作

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int retVal;
    FILE *fp;
    char buffer[] = "Writing to a file using fwrite.";

    fp = fopen("data.txt","w");
    retVal = fwrite(buffer,sizeof(buffer),1,fp);
    
    cout << "fwrite returned " << retVal;
    return 0;
}

运行程序时,buffer 的内容将被写入文件,输出将是

fwrite returned 1

示例 2:当 count 或 size 为零时,fwrite() 函数如何工作

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int retVal;
    FILE *fp;
    char buffer[] = "Writing to a file using fwrite.";

    fp = fopen("myfile.txt","w");
    
    retVal = fwrite(buffer,sizeof(buffer),0,fp);
    cout << "When count = 0, fwrite returned " << retVal << endl;
    
    retVal = fwrite(buffer,0,1,fp);
    cout << "When size = 0, fwrite returned " << retVal << endl;
    
    return 0;
}

运行程序后,输出将是

When count = 0, fwrite returned 0
When size = 0, fwrite returned 0

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战