📜  C++ fwrite()

📅  最后修改于: 2020-09-25 08:25:40             🧑  作者: Mango

C++中的fwrite() 函数将指定数量的字符写入给定的输出流。

fwrite()原型

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

所述fwrite() 函数将count对象的数目,每个尺寸的size字节给定的输出流。

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

它在头文件中定义。

fwrite()参数

fwrite()返回值

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

示例1:fwrite() 函数的工作方式

#include 
#include 

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;
}

当您运行程序时,缓冲区的内容将被写入文件,输出将是:

fwrite returned 1

示例2:当count或size为零时fwrite() 函数的工作方式

#include 
#include 

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