Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ Ostream::write() function



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.

Syntax

Following is the syntax for std::ostream::write() function.

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

Parameters

  • s − It indicates the pointer to an array of at least n characters.
  • n − It indicates the number of characters to insert.

Return Value

It returns the ostream object (*this).

Exceptions

If an exception is thrown, the object is in a valid state.

Data races

Modifies the stream objectAccess up to n characters pointed by s./p>

Example

In 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 −

TUTORIALSPOINT

Example

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 −

Hi

Example

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
Advertisements