The C++ std::ostream::write() function is used to write a block of binary data to an output stream. Unlike typical insertion (<<) operation, which formats data, write() handles unformatted binary data, writing exactly the specified number of bytes. This function takes two arguments: a pointer to the data buffer and the number of bytes to write.
SyntaxFollowing is the syntax for std::ostream::write() function.
ostream& write (const char* s, streamsize n);Parameters
It returns the ostream object (*this).
ExceptionsIf an exception is thrown, the object is in a valid state.
Data racesModifies the stream objectAccess up to n characters pointed by s./p>
ExampleIn the following example, we are going to consider the basic usage of the write() function.
#include <iostream> int main() { const char* x = "TUTORIALSPOINT"; std::cout.write(x, 14); return 0; }Output
Output of the above code is as follows −
TUTORIALSPOINTExample
Consider the following example, where we are going to write only 2 characters of the string message to output.
#include <iostream> int main() { const char *message = "Hi, Namaste"; std::cout.write(message, 2); return 0; }Output
Following is the output of the above code −
HiExample
Let's look at the following example, where we are going to write the binary representation of the integer to the output.
#include <iostream> int main() { int a = 121; std::cout.write(reinterpret_cast<char*>(&a), sizeof(a)); return 0; }Output
If we run the above code it will generate the following output −
y...
ostream.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4