public member function

std::ostream::write

<ostream>
ostream& write ( const char* s , streamsize n );
Write block of data
Writes the block of data pointed by s, with a size of n characters, into the output buffer. The characters are written sequentially until n have been written.

This is an unformatted output function and what is written is not necessarily a c-string, therefore any null-character found in the array s is copied to the destination and does not end the writing process.

Parameters

s
Pointer to a block data with the content to be written.
n
Integer value of type streamsize representing the size in characters of the block of data to write.

Return Value

The function returns *this.

In case of error, the badbit flag is set (which can be checked with member bad). Also, depending on the values set through member exceptions, this may cause an exception of type ios_base::failure to be thrown.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Copy a file
#include <fstream>
using namespace std;

int main () {

  char * buffer;
  long size;

  ifstream infile ("test.txt",ifstream::binary);
  ofstream outfile ("new.txt",ofstream::binary);

  // get size of file
  infile.seekg(0,ifstream::end);
  size=infile.tellg();
  infile.seekg(0);

  // allocate memory for file content
  buffer = new char [size];

  // read content of infile
  infile.read (buffer,size);

  // write to outfile
  outfile.write (buffer,size);
  
  // release dynamically-allocated memory
  delete[] buffer;

  outfile.close();
  infile.close();
  return 0;
}


This example copies a file into memory and then writes its content to a new file.

Basic template member declaration

(basic_ostream<charT,traits>)
1
2
typedef charT char_type;
basic_ostream& write (const char_type* str, streamsize n);


See also