cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : IOstream Library : ostream : write
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
IOstream Library
manipulators
classes:
· filebuf
· fstream
· ifstream
· ios
· iostream
· ios_base
· istream
· istringstream
· ofstream
· ostream
· ostringstream
· streambuf
· stringbuf
· stringstream
objects:
· cerr
· cin
· clog
· cout
types:
· fpos
· streamoff
· streampos
· streamsize
ostream
· ostream::ostream
· ostream::~ostream
member classes:
· ostream::sentry
member functions:
· ostream::flush
· ostream::operator<<
· ostream::put
· ostream::seekp
· ostream::tellp
· ostream::write

-

ostream::write public member function
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 input function and what is inserted is not necessarily a c-string format, therefore any null-character found in the array 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 be read.

Return Value

The functions return *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

// 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>)
typedef charT char_type;
basic_ostream& put (const char_type* str, streamsize n);

See also

ostream::put Put character (public member function)
ostream::operator<< Insert data with format (public member function)
istream::read Read block of data (public member function)

© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us