命名空间
变体
操作

std::fwrite

来自 cppreference.cn
< cpp‎ | io‎ | c
 
 
 
 
定义于头文件 <cstdio>
std::size_t fwrite( const void* buffer, std::size_t size, std::size_t count, std::FILE* stream );

从给定的数组 buffer 向输出流 stream 写入最多 count 个二进制对象。 对象的写入方式如同将每个对象重新解释为 unsigned char 数组,并为每个对象调用 std::fputc size 次,以将这些 unsigned char 写入到 stream 中,按顺序进行。 流的文件位置指示器会前进写入的字符数。

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

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

内容

[编辑] 参数

buffer - 指向要写入的数组中第一个对象的指针
size - 每个对象的大小
count - 要写入的对象的数量
stream - 要写入的输出文件流

[编辑] 返回值

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

如果 sizecount 为零,则 fwrite 返回零,并且不执行其他操作。

[编辑] 示例

#include <array>
#include <cstdio>
#include <vector>
 
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.data(), sizeof rbuf[0], rbuf.size(), f2);
        std::fclose(f2);
        for (std::size_t n = 0; n < sz; ++n)
            std::printf("%d\n", rbuf[n]);
    }
}

输出

42
-1
7

[编辑] 参见

stdout、文件流或缓冲区打印格式化输出
(函数) [编辑]
向文件流写入字符串
(函数) [编辑]
从文件读取
(函数) [编辑]
C 文档 关于 fwrite