Namespaces
Variants

std::basic_ostream<CharT,Traits>:: write

From cppreference.net
basic_ostream & write ( const char_type * s, std:: streamsize count ) ;

表现为一个 非格式化输出函数 。在构造并检查哨兵对象后,从以 s 指向首元素的字符数组中的连续位置输出字符。字符将被插入到输出序列中,直到出现以下情况之一:

  • 恰好插入 count 个字符
  • 向输出序列插入失败(此时将调用 setstate ( badbit )

目录

参数

s - 指向要写入的字符串的指针
count - 要写入的字符数

返回值

* this

异常

failure if an error occurred (the error state flag is not goodbit ) and exceptions() is set to throw for that state.

如果内部操作抛出异常,该异常会被捕获并设置 badbit 。如果为 badbit 设置了 exceptions() ,则异常会被重新抛出。

注释

该函数未针对 signed char unsigned char 类型进行重载,这与格式化的 operator<< 不同。

与格式化输出函数不同,此函数在失败时不会设置 failbit

当使用非转换区域设置(默认区域设置为非转换)时, std::basic_ofstream 中此函数的重写可通过覆盖 std::streambuf::xsputn 实现零拷贝批量I/O优化。

示例

此函数可用于输出对象表示,即二进制输出

#include <iostream>
int main()
{
    int n = 0x41424344;
    std::cout.write(reinterpret_cast<char*>(&n), sizeof n) << '\n';
    char c[] = "This is sample text.";
    std::cout.write(c, 4).write("!\n", 2);
}

可能的输出:

DCBA
This!

参见

插入字符数据或插入到右值流
(函数模板)
插入单个字符
(公开成员函数)