首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::fwrite

Defined in header <cstdio>

?

?

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

?

?

写到count来自给定数组的二进制对象buffer到输出流stream对象的写入方式,就好像通过将每个对象作为unsigned char和呼叫std::fputcsize每个对象编写这些unsigned charstream,按顺序排列。流的文件位置指示符由所写入的字符数提前。

如果对象不是TriviallyCopyable,该行为是未定义的。

如果发生错误,流的文件位置指示符的结果值是不确定的。

参数

buffer

-

pointer to the first object object in the array to be written

size

-

size of each object

count

-

the number of the objects to be written

stream

-

output file stream to write to

返回值

成功写入的对象数量,可能少于count如果发生错误。

如果sizecount是零,fwrite返回零,不执行其他操作。

二次

代码语言:javascript
复制
#include <cstdio>
#include <vector>
#include <array>
 
int main ()
{
    // write buffer to file
    if(std::FILE* f1 = std::fopen("file.bin", "wb")) {
        std::array<int, 3> v = {42, -1, 7}; // underlying storage of std::array is an array
        std::fwrite(v.data(), sizeof v[0], v.size(), f1);
        std::fclose(f1);
    }
 
    // read the same data and print it to the standard output
    if(std::FILE *f2 = std::fopen("file.bin", "rb")) {
        std::vector<int> rbuf(10); // underlying storage of std::vector is also an array
        std::size_t sz = std::fread(&rbuf[0], sizeof rbuf[0], rbuf.size(), f2);
        std::fclose(f2);
        for(std::size_t n = 0; n < sz; ++n) {
            std::printf("%d\n", rbuf[n]);
        }
    }
}

二次

产出:

二次

代码语言:javascript
复制
42
-1
7

二次

另见

printffprintfsprintfsnprintf (C++11)

prints formatted output to stdout, a file stream or a buffer (function)

fputs

writes a character string to a file stream (function)

fread

reads from a file (function)

c编写fwrite文档

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com