C++ Ostream::write() 函式



C++ 的std::ostream::write() 函式用於將一段二進位制資料寫入輸出流。與通常的插入(<<)操作(格式化資料)不同,write() 處理未格式化的二進位制資料,寫入指定數量的位元組。此函式接受兩個引數:指向資料緩衝區的指標和要寫入的位元組數。

語法

以下是 std::ostream::write() 函式的語法。

ostream& write (const char* s, streamsize n);

引數

  • s - 指示指向至少包含 n 個字元的陣列的指標。
  • n - 指示要插入的字元數。

返回值

它返回 ostream 物件(*this)。

異常

如果丟擲異常,則物件處於有效狀態。

資料競爭

修改流物件訪問由 s 指向的最多 n 個字元。

示例

在下面的示例中,我們將考慮 write() 函式的基本用法。

#include <iostream>
int main()
{
    const char* x = "TUTORIALSPOINT";
    std::cout.write(x, 14);
    return 0;
}

輸出

以上程式碼的輸出如下:

TUTORIALSPOINT

示例

考慮以下示例,我們將僅將字串 message 的 2 個字元寫入輸出。

#include <iostream>
int main()
{
    const char *message = "Hi, Namaste";
    std::cout.write(message, 2);
    return 0;
}

輸出

以下是以上程式碼的輸出:

Hi

示例

讓我們看下面的示例,我們將把整數的二進位制表示寫入輸出。

#include <iostream>
int main()
{
    int a = 121;
    std::cout.write(reinterpret_cast<char*>(&a), sizeof(a));
    return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

y...
ostream.htm
廣告

© . All rights reserved.