跳到主要内容

C++ fwrite() 函数

fwrite() 原型

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

fwrite() 函数向给定的输出流写入 count 个对象,每个对象大小为 size 字节。

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

  • 如果对象不是可平凡复制的,行为是未定义的。
  • 如果 sizecount 为零,对 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[] = "使用 fwrite 写入文件。";

fp = fopen("data.txt", "w");
retVal = fwrite(buffer, sizeof(buffer), 1, fp);

cout << "fwrite 返回了 " << retVal;
return 0;
}

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

fwrite 返回了 1

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

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
int retVal;
FILE *fp;
char buffer[] = "使用 fwrite 写入文件。";

fp = fopen("myfile.txt", "w");

retVal = fwrite(buffer, sizeof(buffer), 0, fp);
cout << "当 count = 0 时,fwrite 返回了 " << retVal << endl;

retVal = fwrite(buffer, 0, 1, fp);
cout << "当 size = 0 时,fwrite 返回了 " << retVal << endl;

return 0;
}

当你运行程序时,输出将是:

当 count = 0 时,fwrite 返回了 0
当 size = 0 时,fwrite 返回了 0