Jump to 
content
HP.com Home Products and Services Support and Drivers Solutions How to Buy
»  Contact HP

 

HP C++

HP C++
Class Library Reference Manual


Previous Contents Index


Chapter 4
iostream Package

Classes in the iostream package provide methods to handle input and output streams, including reading and writing built-in data types. You also can extend certain methods described here to handle class types.

This package includes, among others, the classes ios and streambuf , and the subclasses derived from these base classes. Figure 4-1 shows the inheritance structure of the iostream package. In the diagram, arrows point from the base classes to derived classes.

The istream (input stream) class supports input operations (extractions); the ostream (output stream) class supports output operations (insertions). The iostream class derives from both istream and ostream , and supports both extractions and insertions.

The following stream objects are predefined:
cin An istream_withassign object linked to standard input
cout An ostream_withassign object linked to standard output
cerr An ostream_withassign object linked to standard error that supports unbuffered output
clog An ostream_withassign object linked to standard error that supports buffered output

To generate output, you apply the insertion operator (<<) to cout , as shown in the following example:


cout << "Hello\n" ; 

Figure 4-1 Inheritance Diagram for the iostream Package


Obtaining input is similar to generating output, except that you apply the extraction operator (>>) to cin , as shown in the following example:


int eye, jay ; 
cin >> eye >> jay ; 

If you include these fragments of code in a program, your system expects users to type in two integer values (for eye and jay ) from a terminal. The iostream package supplies predefined extraction and insertion operators for all built-in data types, including char* .

This package also supports file manipulation. To connect a specific file to your program, instantiate one of the following class types:

ifstream (for file input)
ofstream (for file output)
fstream (for both input and output)

To format within character arrays, the iostream package includes the following associated class types:

istrstream (for fetching characters from an array)
ostrstream (for storing characters into an array)
strstream (for both fetching and storing characters into an array)

Note

On systems with IEEE floating-point arithmetic, certain values may be printed as symbols for Infinity (for example, INF ) or Not a Number (for example, NaN ).

Deriving Your Own Class from ios

If you derive your own class from the ios class, or from one of its derived classes, the ios subobject must be initialized properly during instantiation. Specifically, you must ensure that the streambuf pointer within the ios subobject is valid.

To do this, you can specify the ios(streambuf *) constructor as a member initializer for your class constructor. Optionally, you can call the ios::init(streambuf *) member function.

Thread Safety

The predefined stream objects, cerr , cin , clog , and cout are thread safe only for individual calls into the C++ Class Library. You must provide synchronization around sequences of calls. For more information on synchronizing access to predefined stream objects, see the section on Global Declarations in this chapter.

User-defined stream objects are not thread safe, so you must provide synchronization around individual calls as well as sequences of calls. For more information on synchronizing access to user-defined objects, see Chapter 6 and the section on Global Declarations in this chapter.

The ios member function sync_with_stdio() is not thread safe. If your application calls this function, it must make the call before any threads use cerr , cin , clog , or cout .


Global Declarations

These declarations are used by the iostream package but they are not members of any class.

Header

#include <iostream.hxx>

Alternative Header

#include <iostream.h>


Declarations


typedef long    streamoff 
typedef long    streampos 
 
ios             &dec(ios &s); 
ios             &hex(ios &s); 
ios             &oct(ios &s); 
ios             &lock(ios &s); 
ios             &unlock(ios &s); 
 
istream         &ws(istream &i); 
ostream         &endl(ostream &o); 
ostream         &ends(ostream &o); 
ostream         &flush(ostream &o); 


Types

typedef long streamoff

Is the type representing a character offset into a stream. For more information, see the description of the seekoff and seekpos functions in the streambuf class.

typedef long streampos

Is the type representing a character position in a stream. For more information, see the description of the seekoff and seekpos functions in the streambuf class.

Manipulators

The following functions insert values into a stream, extract values from a stream, or specify the conversion base format. For more information on the conversion base format flags, see the ios class.

ios &dec(ios &s)

Sets the conversion base format for s to decimal, essentially clearing the ios::oct and ios::hex flags and setting the ios::dec flag.

ios &hex(ios &s)

Sets the conversion base format for s to hexadecimal, essentially clearing the ios::oct and ios::dec flags and setting the ios::hex flag.

ios &oct(ios &s)

Sets the conversion base format for s to octal, essentially clearing the ios::dec and ios::hex flags and setting the ios::oct flag.

istream &ws(istream &i)

Extracts (skips) white-space characters from i.

ostream &endl(ostream &o)

Ends a line by inserting a new-line character into o and flushing o.

ostream &ends(ostream &o)

Ends a string by inserting a null '/0' character into o.

ostream &flush(ostream &o)

Flushes o.

Synchronizing Access to Predefined Stream Objects

The following unparameterized manipulators are for use in synchronizing access to the predefined stream objects, cerr , cin , clog , and cout :

ios &lock(ios &s)

Locks s if s is one of the predefined stream objects.

ios &unlock(ios &s)

Unlocks s if s is one of the predefined stream objects.

If your application needs to lock two or more of these objects at the same time, your application must adhere to the following locking order:

  1. cin
  2. cerr
  3. clog
  4. cout

For example, if your application needs to lock both cerr and cout , lock cerr first and cout second. The unlocking order is not important.

Keep in mind that when your application calls a member function for a predefined stream object, the member function will typically lock the object for the duration of the call. Therefore, if your application has locked one of the stream objects and then uses another, this use must also adhere to the predefined locking order. For example, your application should not send output to cerr while cout is locked.

The locking order necessarily matches the default ties between the stream objects as follows:

cin is tied to cout
cerr is tied to cout
clog is tied to cout
cout has no ties

Any input/output operation on a stream object causes the iostream package to flush the object to which it is tied. Thus, an output to cerr flushes cout .


Examples

#1

#include <iostream.hxx> 
#include <iomanip.hxx> 
 
int main () 
{ 
   int value = 10; 
 
   cout << hex << value << ',';   // Change the base conversion format to 
                                  // hexadecimal; note that the default is 
                                  // decimal as set by the ios constructors. 
 
   cout << value << ',';          // The base conversion format set in the 
                                  // previous line is still active.      
 
   cout << dec << value << endl;  // Change the base conversion format to 
                                  // decimal; lastly, insert a new-line 
                                  // character into the stream and flush 
                                  // cout. 
   return 0; 
} 
      

The output is a,a,10.

#2

#include <string.hxx> 
#include <iostream.hxx> 
 
void print_name(String &name) 
{ 
   cout << lock << "Hello, " << name << endl << unlock; 
} 
      

This synchronizes access to the cout object so that the "Hello, " , name, and new-line character are written to cout as a single unit. If you do not use the lock and unlock manipulators in this example, another thread could possibly insert its own text into cout in the midst of your output.


Header

#include <iomanip.hxx>

Alternative Header

#include <iomanip.h>


Declarations


 
SMANIP(long)       resetiosflags(long); 
SMANIP(long)       setiosflags(long); 
SMANIP(int)        setfill(int); 
SMANIP(int)        setprecision(int); 
SMANIP(int)        setw(int w); 
 
SMANIPREF(Mutex)   lock(Mutex &m) 
SMANIPREF(Mutex)   unlock(Mutex &m) 


Functions

These functions are used for extending the iostream package with user-defined parameterized manipulators.

SMANIP(long) resetiosflags(long x)

In the stream ( ios or a stream derived from ios ), clears the format flags denoted by x.

SMANIP(int) setfill(int x)

Sets the fill character to be the value specified by x. The fill character is a data member of the ios class; however, setting it with this function affects only output streams.

SMANIP(long) setiosflags(long x)

In the stream ( ios or a stream derived from ios ), turns on the format flags denoted by x. If you are setting a flag that is part of a collection (for example, basefield ), note that this manipulator does not clear the other flags in the collection.

SMANIP(int) setprecision(int x)

Sets the variable that controls the number of digits inserted by the floating-point inserter to be x. This variable is a data member of the ios class; however, setting it with this function affects only output streams.

SMANIP(int) setw(int w)

In the stream ( ios or a stream derived from ios ), sets the field width of the stream to w.

Synchronizing Access to User-Defined Stream Objects

The following parameterized manipulators are for use in synchronizing access to user-defined stream objects. To use these manipulators, you must first define a Mutex object, which you then pass to the manipulator. The association of a Mutex object with a stream object is not enforced by the iostream package. This association is enforced only by you, the programmer. Refer to Chapter 6 for information on the Mutex class.

SMANIPREF(Mutex) lock(Mutex &m)

Locks the recursive Mutex represented by m.

SMANIPREF(Mutex) unlock(Mutex &m)

Unlocks the recursive Mutex represented by m.

Examples

#1

char c; 
cin >> resetiosflags(ios::skipws) 
    >> c 
    >> setiosflags(ios::skipws); 
      

Turns off the flag (resets it to 0) that tells the extractor (>>) to skip leading white space and then turns that flag back on again (sets it to 1).

#2

cout.fill(*) 
cout.setf(ios::left,ios::adjustfield); 
cout << setw(6) << 23 << "," ; 
cout.fill(%); 
cout.setf(ios::right,ios::adjustfield); 
cout << setw(4) << 34 << "\n" ; 
      

Places padding characters (specified by the fill state variable) after the first number and before the second number. The output is 23****,%%34 .

#3

#include <string.hxx> 
#include <fstream.hxx> 
#include <mutex.hxx> 
#include <iomanip.hxx> 
 
main () 
{ 
   String name("Henry"); 
   void print_name (String &, ostream &, Mutex &); 
 
   ofstream mystream(1); 
   Mutex mystream_lock; 
 
   print_name(name, mystream, mystream_lock); 
   return 0; 
} 
 
   void print_name(String &name, ostream &stream, Mutex &stream_lock) 
{ 
      stream << lock(stream_lock) << "Hello, " << name << endl 
             << unlock(stream_lock); 
} 
      

This example associates a Mutex object with a stream object to synchronize access to the stream. The Mutex is locked before using the stream and then unlocked afterwards. For the synchronization to work properly, each thread that uses this stream must perform the same lock/unlock sequence with the same Mutex.


See Also

IMANIP(TYPE) class
IOMANIP(TYPE) class
OMANIP(TYPE) class
SMANIP(TYPE) class

filebuf class

Provides a data buffer abstraction for input/output facilities through file descriptors.

Header

#include <fstream.hxx>

Alternative Header

#include <fstream.h>


Declaration


class filebuf: public streambuf 
{ 
public: 
    static const int    openprot; 
 
                        filebuf(); 
                        filebuf(int fd); 
                        filebuf(int fd, char *p, int len); 
                        ~filebuf(); 
 
    filebuf             *attach(int fd); 
    filebuf             *close(); 
    int                 fd(); 
    int                 is_open(); 
    filebuf             *open(const char *name, int mode, 
                        int prot = openprot); 
 
    virtual int         overflow(int = EOF); 
    virtual streampos   seekoff(streamoff, seek_dir, int mode); 
    virtual streampos   seekpos(streampos, int mode); 
    virtual streambuf   *setbuf(char *p, int len); 
    virtual int         sync(); 
    virtual int         underflow(); 
}; 


Description

This class specializes the streambuf class to use a file as a repository of characters. Writing to the file consumes characters; reading from the file produces characters. Files that allow searches are said to be seekable. When a file is readable and writable, the filebuf object permits character insertion and extraction.

If your program expects a buffer to be allocated when none was allocated, then the iostream package allocates a default buffer with a length specified by BUFSIZ as defined in stdio.h . The package then issues the following warning:


Warning; a null pointer to streambuf was passed to ios::init() 


Data Member

const int openprot = 0644

Provides default protection for the open() function. (For an explanation of the file protection, see the C Run-Time Library Reference Manual.)

Constructors and Destructors

filebuf()

Constructs a filebuf object that is initially closed.

filebuf(int fd)

Constructs a filebuf object connected to file descriptor fd.

filebuf(int fd, char *p, int len)

Constructs a filebuf object connected to file descriptor fd, which is initialized to use the reserve area (buffer) starting at p and containing len bytes.

~filebuf()

Deletes a filebuf object.

Member Functions

filebuf *attach(int fd)

Connects the filebuf object to an open file whose descriptor is passed through the fd argument. It normally returns a reference to the filebuf object, but returns 0 if the filebuf object is connected to an open file.

filebuf *close()

Flushes any waiting output, closes the file descriptor, and disconnects a filebuf object. Unless an error occurs, the filebuf object's error state will be cleared. The close() function returns the address of the filebuf object unless errors occur, in which case this function returns 0. Even if errors occur, close() leaves the file descriptor and filebuf object closed.

int fd()

Returns the file descriptor associated with a filebuf object. If the filebuf object is closed, fd returns EOF .

int is_open()

Returns a nonzero value when a filebuf object is connected to a file descriptor; otherwise, it returns 0.

filebuf *open(const char *name, int mode, int prot)

Opens a file with the name specified by name and connects a filebuf object to it. If the file does not exist, the function tries to create it with the protection mode prot unless ios::nocreate is specified in mode. By default, prot is filebuf::openprot .

The function fails if the filebuf object is open. The open() function normally returns the address of the filebuf object, but returns 0 if an error occurs. The members of open_mode are bits that may be joined together by or (because this joining takes an int , open() takes an int rather than an open_mode argument). For an explanation of the meanings of these bits in open_mode , see the Enumerated Types section for the ios class.

virtual int overflow(int c)

Called to consume characters in classes derived from streambuf . If c is not EOF , this function must also either save c or consume it. Although it can be called at other times, this function usually is called when the put area is full and an attempt is being made to store a new character. The normal action is to consume the characters between pbase() and pptr() , call setp() to establish a new put area, and (if c != EOF ) store c using sputc() . A call to overflow(c) should return EOF to indicate an error; otherwise, it should return something else.

virtual streampos seekoff(streamoff off, seek_dir dir, int mode)

Moves the get pointer, put pointer, or both as designated by the off and dir arguments. It may fail if the file does not support seeking, or if the attempted motion is otherwise invalid (for example, attempting to seek a position before the beginning of the file). The off argument is interpreted as a count relative to the place in the file specified by dir. The mode argument is ignored. A call to seekoff() returns the new position or EOF if a failure occurs. After a failure, the position of the file is undefined.

virtual streampos seekpos(streampos pos, int mode)

Moves the file to a position pos. The mode argument is ignored. The function normally returns pos but it returns EOF on failure.

virtual streambuf *setbuf(char *p, int len)

Sets up the reserve area as the number of bytes specified in the second argument, beginning at the pointer specified in the first argument. If the pointer is null, or the number of bytes is less than 1, the filebuf object is unbuffered. This function normally returns a pointer to the filebuf object; however, if the filebuf object is open and a buffer is allocated, then no changes are made to the reserve area and to the buffering status, and setbuf() returns 0.

virtual int sync()

Tries to get the state of the get pointer, the put pointer, or both, to agree (synchronize) with the state of the file to which the filebuf object is connected. This means that the function may write characters to the file if some of the characters have been buffered for output, or the function may try to reposition (seek) the file if characters have been read and buffered for input. Normally sync() returns 0, but it returns EOF if synchronization is not possible.

When certain characters must be written together, the program should use setbuf() (or a constructor) to ensure that the reserve area is at least as large as the number of characters to be written together. Your program can then call sync() , store the characters, and then call sync() once again.

virtual int underflow()

Called in classes derived from streambuf to supply characters for fetching; that is, to create a condition in which the get area is not empty. If the function is called when characters occupy the get area, it should create a nonempty area and return the next character (which it should also leave in the get area). If no more characters are available, underflow() should return EOF and leave an empty get area.

See Also

ios class
streambuf class

fstream class

Supports formatted and unformatted input from and output to files.

Header File

#include <fstream.hxx>

Alternative Header

#include <fstream.h>


Declaration


class fstream: public iostream 
{ 
public: 
                 fstream(); 
                 fstream(const char *name, int mode, 
                     int prot = filebuf::openprot); 
                 fstream(int fd); 
                 fstream(int fd, char *p, int len); 
                 ~fstream(); 
 
    void         attach(int fd); 
    void         close(); 
    void         open(const char *name, int mode, 
                     int prot = filebuf::openprot) ; 
    filebuf      *rdbuf(); 
    void         setbuf(char *p, int len); 
}; 


Description

This class specializes the iostream class to files by using a filebuf object to do the input and output. Your program can perform common operations, such as opening and closing files, without explicitly mentioning filebuf objects.


Constructors and Destructors

fstream()

Constructs an unopened fstream object.

fstream(int fd)

Constructs an fstream object connected to the file whose descriptor is passed through the fd argument. The file must be open.

fstream(int fd, char *p, int len)

Constructs an fstream object connected to a file whose descriptor is passed through the fd argument, and also initializes the associated filebuf object to use the len bytes starting at p as the reserve area. If p is null or len is 0, the filebuf object is unbuffered.

fstream(const char *name, int mode, int prot)

Constructs an fstream object and opens the file specified by the name argument. The mode and prot arguments specify the file open mode and protection. By default, prot is filebuf::openprot . If the open action fails, the error state ( io_state ) of the constructed fstream object indicates failure.

~fstream()

Deletes an fstream object.

Member Functions

void attach(int fd)

Connects an fstream object to a file whose descriptor is passed through the fd argument. A failure occurs when the fstream object is connected to a file, in which case ios::failbit is set in the filebuf object's error state.

void close()

Closes any associated filebuf object and consequently breaks the connection of the fstream object to the file. The error state of the fstream object is cleared except on failure. A failure occurs when the call to the filebuf object's close() function fails.

void open(const char *name, int mode, int prot)

Opens a file with the file name specified by name and connects the fstream object to it. If the file does not exist, the function tries to create it with the protection specified by the prot argument unless ios::nocreate is set. By default, prot is filebuf::openprot .

Failure occurs if the fstream object is open or when the call to the filebuf object's open() function fails, in which case ios::failbit is set in the filebuf object error state. The members of open_mode are bits that may be joined together by or (because this joining takes an int , open() takes an int rather than an open_mode argument). For an explanation of the meanings of these bits in open_mode , see the Enumerated Types section for the ios class.

filebuf *rdbuf()

Returns a pointer to the filebuf object associated with the fstream object. This function has the same meaning as ios::rdbuf() , but has a different type.

void setbuf(char *p, int len)

Calls the associated filebuf object setbuf() function to request space for a reserve area. A failure occurs if the filebuf object is open or if the call to rdbuf()->setbuf fails for any other reason.

IAPP(TYPE) class

For an istream object, declares predefined parameterized applicators.

Header File

#include <iomanip.hxx>

Alternative Header

#include <iomanip.h>


Compile-Time Parameter

TYPE---The type of the istream object. It must be an identifier.

Declaration


class IAPP(TYPE) 
{ 
public: 
    IAPP(TYPE)(istream &(*f)(istream &, TYPE)); 
    IMANIP(TYPE) operator()(TYPE a); 
}; 


Constructor

IAPP(TYPE) (istream &(*f) (istream &, TYPE))

Creates an applicator; *f is the left operand of the insertion operator.

Operator

IMANIP(TYPE) operator () (TYPE a)

Casts an object of type a into a manipulator function for an istream object.

See Also

IMANIP(TYPE) class

ifstream class

Supports formatted and unformatted input from files.

Header File

#include <fstream.hxx>

Alternative Header

#include <fstream.h>


Declaration


class ifstream: public istream 
{ 
public: 
                ifstream(); 
                ifstream(const char *name, int mode = ios::in, 
                     int prot = filebuf::openprot); 
                ifstream(int fd); 
                ifstream(int fd, char *p, int len); 
                ~ifstream(); 
 
    void        attach(int fd); 
    void        close(); 
    void        open(const char *name, int mode = ios::in, 
                     int prot = filebuf::openprot); 
    filebuf     *rdbuf(); 
    void        setbuf(char *p, int len); 
}; 


Description

This class specializes the istream class to files by using a filebuf object to do the input. Your program can perform common operations, such as opening and closing files, without explicitly mentioning filebuf objects.


Constructors and Destructors

ifstream()

Constructs an unopened ifstream object.

ifstream(int fd)

Constructs an ifstream object connected to a file whose descriptor is passed through the fd argument. The file must already be open.

ifstream(int fd, char *p, int len)

Constructs an ifstream object connected to a file whose descriptor is passed through the fd argument, and also initializes the associated filebuf object to use the len bytes starting at p as the reserve area. If p is null or len is 0, the filebuf object is unbuffered.

ifstream(const char *name, int mode, int prot)

Constructs an ifstream object and opens the file with the file name specified by name. The mode and prot arguments specify the file open mode and protection. By default, prot is filebuf::openprot . If the open fails, the error state ( io_state ) of the constructed ifstream object indicates failure.

~ifstream()

Deletes an ifstream object.

Member Functions

void attach(int fd)

Connects an ifstream object to a file whose descriptor is passed through the fd argument. A failure occurs when the ifstream object is connected to a file, in which case ios::failbit is set in the ifstream object error state.

void close()

Closes any associated filebuf object and consequently breaks the connection of the ifstream object to the file. The error state of the fstream object is cleared except on failure. A failure occurs when the call to the filebuf object's close() function fails.

void open(const char *name, int mode, int prot)

Opens a file specified by the name argument and connects the ifstream object to it. If the file does not exist, the function tries to create it with the protection specified by the prot argument unless ios::nocreate is set. By default, prot is filebuf::openprot .

Failure occurs if the ifstream object is open or when the call to the filebuf object open() function fails, in which case ios::failbit is set in the filebuf object error state. The members of open_mode are bits that may be joined together by or (because this joining takes an int , open() takes an int rather than an open_mode argument). For an explanation of the meanings of these bits in open_mode , see the Enumerated Types section for the ios class.

filebuf *rdbuf()

Returns a pointer to the filebuf object associated with the ifstream object. This function has the same meaning as ios::rdbuf() but has a different type.

void setbuf(char *p, int len)

Calls the associated filebuf object setbuf() function to request space for a reserve area. A failure occurs if the filebuf object is open or if the call to rdbuf()->setbuf fails for any other reason.

IMANIP(TYPE) class

For an istream object, declares the predefined parameterized manipulators and provides macros for user-defined parameterized manipulators.

Header File

#include <iomanip.hxx>

Alternative Header

#include <iomanip.h>


Compile-Time Parameter

TYPE---The type of the istream object. It must be an identifier.

Declaration


 
class IMANIP(TYPE) 
{ 
public: 
    IMANIP(TYPE)(istream &(*f)(istream &, TYPE), TYPE a); 
    friend istream &operator>>(istream &s, IMANIP(TYPE) &m); 
}; 


Description

These manipulators serve the istream class by producing some useful effect, such as embedding a function call in an expression containing a series of insertions and extractions. You also can use manipulators to shorten the long names and sequences of operations required by the iostream class.

In its simplest form, a manipulator takes an istream& argument, operates on it in some way, and returns it.


Constructor

IMANIP(TYPE)(istream &(*f)(istream &, TYPE), TYPE a)

Creates a manipulator; *f is the left operand of the extractor operator.

Operator

istream &operator >> (istream &s, IMANIP(TYPE) &m)

Takes data from an istream object.

IOAPP(TYPE) class

For an iostream object, declares predefined parameterized applicators.

Header File

#include <iomanip.hxx>

Alternative Header

#include <iomanip.h>


Compile-Time Parameter

TYPE---The type of the iostream object. It must be an identifier.

Declaration


class IOAPP(TYPE) 
{ 
public: 
    IOAPP(TYPE)(iostream &(*f)(iostream &, TYPE)); 
    IOMANIP(TYPE) operator()(TYPE a); 
}; 


Constructor

IOAPP(TYPE)(iostream &(*f)(iostream &, TYPE))

Creates an applicator.

Operator

IOMANIP(TYPE) operator () (TYPE a)

Casts an object of type a into a manipulator function for an iostream object.

See Also

IOMANIP(TYPE) class

IOMANIP(TYPE) class

For an iostream object, declares predefined parameterized manipulators and provides macros for user-defined parameterized manipulators.

Header File

#include <iomanip.hxx>

Alternative Header

#include <iomanip.h>


Compile-Time Parameter

TYPE---The type of the iostream object. It must be an identifier.

Declaration


class IOMANIP(TYPE) 
{ 
public: 
    IOMANIP(TYPE)(iostream &(*f)(iostream &, TYPE), TYPE a); 
    friend istream &operator>>(iostream &s, IOMANIP(TYPE) &m); 
    friend ostream &operator<<(iostream &s, IOMANIP(TYPE) &m); 
}; 
 
IOMANIPdeclare(int); 
IOMANIPdeclare(long); 


Description

These manipulators serve the iostream class by producing some useful effect, such as embedding a function call in an expression containing a series of insertions and extractions. You can also use manipulators to shorten the long names and sequences of operations required by the iostream class.

In its simplest form, a manipulator takes an iostream& argument, operates on it in some way, and returns it.

Two ios manipulators for using Mutex objects, lock and unlock , come in both parameterized and unparameterized forms. The parameterized manipulators let users synchronize iostream objects, the parameter being a user-defined Mutex object. To use parameterized manipulators, you must include iomanip.hxx . Unparameterized manipulators let users synchronize the predefined stream objects: cerr , cin , clog , and cout .

For examples of using the lock and unlock manipulators, see Chapter 6 and the section on Global Declarations in this chapter.


Constructor

IOMANIP(TYPE)(iostream &(*f)(iostream &, TYPE), TYPE a)

Creates a manipulator.

Macro

IOMANIPdeclare(TYPE)

Declares the manipulators (and the manipulator classes) that have an operator() member function for type TYPE.

Operators

ostream &operator << (iostream &s, IOMANIP(TYPE) &m)

Sends data to an iostream object.

istream &operator >> (iostream &s, IOMANIP(TYPE) &m)

Takes data from an iostream object.

ios class

Contains state variables common to most of the other classes in the iostream package.

Header

#include <iostream.hxx>

Alternative Header

#include <iostream.h>


Declaration


class ios 
{ 
public: 
    enum io_state       { goodbit = 0, eofbit = 01, 
                          failbit = 02, badbit = 04 }; 
    enum open_mode      { in = 01, out = 02, ate = 04, 
                          app = 010, trunc = 020, 
                          nocreate = 040, noreplace = 0100 }; 
    enum seek_dir       { beg = 0, cur = 01, end = 02 }; 
 
    enum                { skipws = 01, 
                          left = 02, right = 04, internal = 010, 
                          dec = 020, oct = 040, hex = 0100, 
                          showbase = 0200, showpoint = 0400, 
                          uppercase = 01000, 
                          showpos = 02000, 
                          scientific = 04000, fixed = 010000, 
                          unitbuf = 020000, stdio = 040000 }; 
 
    static const long   basefield; 
    static const long   adjustfield; 
    static const long   floatfield; 
 
                        ios(streambuf *); 
    virtual             ~ios(); 
 
    inline int          bad() const; 
    static long         bitalloc(); 
    inline void         clear(int state = 0); 
    inline int          eof() const; 
    inline int          fail() const; 
    inline char         fill() const; 
    char                fill(char); 
    inline long         flags() const; 
    long                flags(long); 
    inline int          good() const; 
    long                &iword(int); 
    inline int          operator!(); 
    inline              operator void *(); 
    inline int          precision() const; 
    int                 precision(int); 
    void                *&pword(int); 
    inline streambuf    *rdbuf(); 
    inline int          rdstate() const; 
    long                setf(long setbits, long field); 
    long                setf(long); 
    static void         sync_with_stdio(); 
    inline ostream      *tie() const; 
    ostream             *tie(ostream *); 
    long                unsetf(long); 
    inline int          width() const; 
    int                 width(int n); 
    static int          xalloc(); 
 
protected: 
                        ios(); 
    void                init(streambuf *); 
    inline void         setstate(int state); 
 
}; 


Description

Classes derived from the ios class provide an interface for transferring formatted and unformatted information into and out of streambuf objects.

Enumerated Types

io_state

Represents a collection of bits (flags) that describe the internal error states of an object. The values are as follows:
goodbit No errors occurred.
eofbit End-of-file encountered during an extraction operation.
failbit Extraction or conversion failed but the stream is still usable.
badbit A severe error, usually in an operation on the associated streambuf object, from which recovery is unlikely.

open_mode

Represents a collection of bits (flags) for specifying the mode of the open() function. Use this data type with objects of the fstream , ifstream , and ofstream classes. The values are as follows:
app Performs a seek to the end-of-file. This appends to the end of the file any subsequent data written to the file. ios::app implies ios::out .
ate Performs a seek to the end-of-file during an open() operation. ios::ate does not imply ios::out .
in Opens the file for input. Constructions and open operations of ifstream objects imply ios::in . For fstream objects, ios::in signifies that input operations should be allowed if possible. Including ios::in in the modes of an ofstream object is legal, implying that the original file (if it exists) should not be truncated.
out Opens the file for output. Constructions and open operations of ofstream objects imply ios::out . For fstream objects, ios::out indicates that output operations are allowed.
trunc Truncates (discards) the contents of the file (if it exists). ios::trunc is implied if ios::out is specified (including implicit specification for ofstream objects), and neither ios::app nor ios::ate is specified.
nocreate Causes an open() operation to fail if the file does not exist.
noreplace Causes an open() operation to fail if the file exists.

seek_dir

Represents a collection of bits for positioning get and put pointers. Use this data type with functions of the filebuf , istream , ostream , and streambuf classes. The values are as follows:
beg Indicates the beginning of the stream
cur Indicates the current position
end Indicates the end of the stream (end-of-file)

Data Members

const long adjustfield

Collectively specifies the flags (bits) that control padding ( left , right , and internal ).

const long basefield

Collectively specifies the flags that control base conversion ( dec , hex , and oct ).

const long floatfield

Collectively specifies the flags that control floating-point value conversion ( fixed and scientific ).

Note

When you set a flag that is part of adjustfield , basefield , or floatfield , you must ensure that the other flags within the collection are cleared. Only one flag within the collection should be set at any one time.

Be aware that the setiosflags(flag) manipulator and the setf(flag) member function set only the flag or flags that you specify. If the flag you specify is part of a collection, these do not clear the other flags in the collection.

The setf(flag, field) member function is useful for setting fields within a collection. Also, the hex , oct , and dec manipulators do ensure that the other flags within the basefield collection are cleared.

Constructors and Destructors

ios()

Constructs an ios object with the effect undefined. It lets derived classes inherit the ios class as a virtual base class. The object is initialized with the following default values:
Element Default Value
fill() The space character
flags() ios::dec | ios::skipws
precision() 6
rdstate() ios::goodbit
width() 0

ios(streambuf *b)

Constructs an ios object, associating the constructed ios object with the streambuf object pointed to by b. The object is initialized with the same default values as the ios() constructor.

virtual ~ios()

Deletes an ios object.

Overloaded Operators

When defined, the following operators allow convenient checking of the error state of an ios .

int operator !()

Returns nonzero if failbit or badbit is set in the error state, which allows the use of such expressions as if (!cin) ....

int operator void *()

Converts an ios object to a pointer so that it can be compared to 0. The conversion returns a nonzero value (not meant for further use) if neither failbit nor badbit is set in the error state. This allows the use of such expressions as if (cin) ... and if (cin >> x) ....

Other Member Functions

int bad() const

Returns a nonzero value if badbit is set in the error state; otherwise, it returns 0. This usually indicates that some operation on rdbuf() has failed, and that continued operations on the associated streambuf object may not be possible.

long bitalloc()

Returns a long integer with a single, previously unallocated bit set. This gives you an additional flag should you need one (to pass to ios::set() , for example).

void clear(int state)

Stores an integer value as the error state. A 0 value clears all bits.

int eof() const

Returns a nonzero value if eofbit is set in the error state; otherwise, it returns 0. This bit is usually set during an extraction and when an end-of-file has been encountered.

int fail() const

Returns a nonzero value if either badbit or failbit is set in the error state; otherwise, it returns 0. This usually indicates that some extraction or conversion operation has failed, but that the stream remains usable; once failbit clears, operations on the stream can usually continue.

char fill() const

Returns the variable currently used as the fill (padding) character.

char fill(char c)

Sets c as the fill (padding) character if one is needed (see width () ) and returns the previous value. The default fill character is a space. The right , left , and internal flags determine positioning of the fill character. A parameterized manipulator, setfill , is also available for setting the fill character.

long flags() const

Returns the current format flags.

long flags(long f)

Resets all the format flags to those specified in f and returns the previous settings. The flags are as follows:
skipws For scalar operations, instructs the arithmetical extractor to skip white space before beginning conversion. As a precaution against looping, arithmetical extractors signal an error if the next character is white space and the skip variable is not set.
left
right
internal
Control padding of values. The left flag adds a fill character after a value, right adds a fill character before a value, and internal adds a fill character after any leading sign or base indication, but before the value. Right-adjustment is the default if none of these flags are set. The fields are collectively identified by the static member ios::adjustfield . The fill character is controlled by the fill() function and the width after the padding is controlled by the width() function.
dec
oct
hex
Control the conversion base of a value. Insertions are in decimal if none of these flags are set. Extractions follow C++ lexical conventions for integral constants. The flags are collectively identified by the static member ios::basefield . The manipulators hex , dec , and oct are also available for setting the conversion base.
showbase Converts insertions to an external form that can be read according to the C++ lexical conventions for integral constants. By default, showbase is not set.
showpos Inserts a plus sign (+) into a decimal conversion of a positive integral value.
uppercase Uses an uppercase X for hexadecimal conversion when showbase is set, or uses uppercase E to print floating-point numbers in scientific notation. By default, uppercase is not set.
showpoint Specifies that trailing zeros and decimal points appear in the result of a floating-point conversion.
scientific
fixed
Control the format to which a floating-point value is converted for insertion into a stream. These two flags are collectively identified by the static member ios::floatfield . The scientific flag converts the value using scientific notation, with one digit before the decimal point. Depending on the uppercase flag, an E or an e introduces the exponent. The fixed flag converts the value to decimal notation. For both flags, the precision function determines the number of digits following the decimal point (6 is the default). If neither flag is set, then scientific notation is used only if the exponent from the conversion is less than --4 or greater than the precision. If showpoint is not set, trailing zeros are removed from the result and a decimal point appears only if followed by a digit.
unitbuf Causes ostream::osfx() to perform a flush after each insertion. Unit buffering constitutes a performance compromise between buffered and unbuffered output.
stdio Causes ostream::osfx() to flush stdout and stderr after each insertion.

int good() const

Returns a nonzero value if the error state has no bits set; otherwise, it returns 0.

void init(streambuf *b)

Initializes the ios object; intended for use by classes derived from ios .

long& iword(int i)

Returns a reference to the ith user-defined word, where i is an index into an array of words allocated by ios::xalloc . 1

int precision() const

Returns the precision format state variable.

int precision(int i)

Sets the precision format state variable to i and returns the previous value. The variable controls the number of significant digits inserted by the floating-point inserter. The default is 6. A parameterized manipulator, setprecision , is also available for setting the precision.

void *&ios::pword(int i)

Returns a reference to the ith user-defined word, where i is an index into an array of words allocated by ios::xalloc . This function differs from iword() only in type.

streambuf *ios::rdbuf()

Returns a pointer to the streambuf object that was associated with an ios object when the ios object was constructed.

int rdstate() const

Returns the current error state.

long setf(long setbits)

Makes available to the streambuf object associated with an ios object the format flags marked in setbits and returns the previous settings. A parameterized manipulator, setiosflags , performs the same function. If you are setting a flag that is part of a collection (for example, basefield ), note that this manipulator does not clear the other flags in the collection.

long setf(long setbits, long field)

Clears, in the streambuf object associated with an ios object, the format flags specified by field, then resets these flags to the settings marked in setbits. It returns the previous settings. Specifying 0 in setbits clears all the bits specified in field, as does the parameterized manipulator, resetioflags .

void setstate(int state)

Changes only the bits specified in the state argument.

void sync_with_stdio()

Solves problems that arise with mixing stdio and iostream objects. When first called, the sync_with_stdio() function resets the standard iostream functions ( cin , cout , cerr , and clog ) to be streams using stdiobuf objects. Subsequently, input and output using these streams may be mixed with input and output using the corresponding FILE parameters ( stdin , stdout , and stderr ), and properly synchronized. The sync_with_stdio() function makes cout and cerr unit buffered (see ios::unitbuf and ios::stdio ). Invoking sync_with_stdio() degrades performance variably; the shorter the strings being inserted, the greater the degradation.

ostream *ios::tie() const

Returns the tie variable (see the following member function description).

ostream *ios::tie(ostream *osp)

Sets the tie variable to osp and returns its previous value. The tie variable supports automatic flushing of ios objects. The ios object that the tie variable points at is flushed if the variable is not null, and an ios object either needs more characters or has characters to be consumed. By default, cin is initially tied to cout so that attempts to get more characters from standard input result in flushing standard output. Additionally, cerr and clog are tied to cout by default. By default, the tie variable is set to 0 for other ios objects.

long unsetf(long setbits)

Unsets, in the streambuf object associated with an ios object, the bits set in setbits; it returns the previous settings.

int width() const

Returns the field-width format variable (see the following member function description). The field width setting within the ios class is ignored during single character output: operator<<(char) and operator<<(unsigned char).

int width(int n)

Sets the field-width format variable to n and returns the previous value. The field width specifies a minimum number of characters for inserters. When the variable is 0 (the default), inserters insert only as many characters as needed to represent the value being inserted. When the variable is nonzero, and the value being inserted needs fewer than field-width characters to be represented, inserters insert at least that many characters using the fill character to pad the value. Numeric inserters do not truncate values even if the value being inserted is more than field-width characters. After each insertion or extraction, the field-width format variable resets to 0. A parameterized manipulator, setw , is also available for setting the field width.

int xalloc()

Returns a previously unused index into an array of words available for use by derived classes as format state variables. 1

Examples

#1

cout.width(6); 
cout << x << " " << y; 
      

Outputs x in at least six characters, but uses only as many characters as needed for the separating space and y .

In the following examples, mystrm is an ios object.

#2

mystrm.clear(ios::badbit|s.rdstate()) 
      

Sets the badbit member of the io_state enumerated data type without clearing previously set bits.

#3

mystrm.setf(ios::hex,ios::basefield) 
      

Changes the conversion base in mystrm to be hexadecimal.

Note

1 This function references a single array that is shared among all instances of ios objects. This differs from the HP UNIX operating system, where this function references the array that is specific to the ios instance.

1 This function references a single array that is shared among all instances of ios objects. This differs from the HP UNIX operating system, where this function references the array that is specific to the ios instance.

iostream class

Provides the means to both insert into and extract from a single sequence of characters.

Header File

#include <iostream.hxx>

Alternative Header

#include <iostream.h>


Declaration


class iostream: public istream, public ostream 
{ 
public: 
               iostream(streambuf *); 
    virtual    ~iostream(); 
 
protected: 
               iostream(); 
}; 


Description

This class combines the istream and ostream classes. You use it to carry out bidirectional operations (inserting into and extracting from a single sequence of characters).

Constructors and Destructors

iostream()

Constructs an iostream object, in undefined form, to enable inheritance by derived classes.

iostream(streambuf *b)

Constructs an iostream object. It initializes ios state variables and associates the iostream object with the streambuf object pointed to by b.

virtual ~iostream()

Deletes an iostream object.

iostream_withassign class

Adds an assignment operator and a constructor with no operands to the iostream class.

Header File

#include <iostream.hxx>

Alternative Header

#include <iostream.h>


Declaration


class iostream_withassign: public iostream 
{ 
public: 
                   iostream_withassign(); 
    virtual       ~iostream_withassign(); 
 
    iostream_withassign &operator=(iostream &); 
    iostream_withassign &operator=(streambuf *); 
}; 


Description

This class adds an assignment operator and a constructor with no operands to the iostream class.

Constructors and Destructors

iostream_withassign()

Constructs an iostream_withassign object; it does no initialization.

virtual ~iostream_withassign()

Deletes an iostream_withassign object; no user action is required.

Overloaded Operators

iostream_withassign &operator = (iostream &)

Associates iostream->rdbuf() with an iostream_withassign object and initializes the entire state of that object.

iostream_withassign &operator = (streambuf *)

Associates streambuf* with an iostream_withassign object and initializes the entire state of that object.

istream class

Supports interpretation of characters extracted from an associated streambuf object.

Header File

#include <iostream.hxx>

Alternative Header

#include <iostream.h>


Declaration


class istream : virtual public ios 
{ 
public: 
                       istream(streambuf *); 
    virtual            ~istream(); 
 
    inline int         gcount(); 
    istream            &get(char *ptr, int len, 
                             char delim = '\n'); 
    istream            &get(unsigned char *ptr, int len, 
                             char delim = '\n'); 
    istream            &get(char &); 
    inline istream     &get(unsigned char &); 
    istream            &get(streambuf &sb, char delim = '\n'); 
    int                get(); 
    istream            &getline(char *ptr, int len, 
                             char delim = '\n'); 
    istream            &getline(unsigned char *ptr, int len, 
                              char delim = '\n'); 
    istream            &ignore(int len = 1, 
                             int delim = ); 
    int                ipfx(int need = 0); 
    void               isfx(); 
    int                peek(); 
    istream            &putback(char); 
    istream            &read(char *s, int n); 
    inline istream     &read(unsigned char *s, int n); 
    istream            &seekg(streampos); 
    istream            &seekg(streamoff, seek_dir); 
    void               skipwhite(); 
    int                sync(); 
    streampos          tellg(); 
    istream            &operator>>(char *); 
    istream            &operator>>(char &); 
    istream            &operator>>(short &); 
    istream            &operator>>(int &); 
    istream            &operator>>(long &); 
    istream            &operator>>(float &); 
    istream            &operator>>(double &); 
    istream            &operator>>(unsigned char *); 
    istream            &operator>>(unsigned char &); 
    istream            &operator>>(unsigned short &); 
    istream            &operator>>(unsigned int &); 
    istream            &operator>>(unsigned long &); 
    istream            &operator>>(streambuf *); 
    inline istream     &operator>>(istream &(*f)(istream &)); 
    istream            &operator>>(ios &(*f)(ios &)); 
 
protected: 
                       istream(); 
 
}; 


Description

This class provides facilities for formatted and unformatted extraction from streambuf objects.

Constructors and Destructors

istream(streambuf *sb)

Constructs an istream object. It initializes ios state variables and associates the istream object with the buffer pointed to by sb.

virtual ~istream()

Deletes an istream object.

Overloaded Operators

The following operators are all formatted input extractors. Given the expression ins >> x, these operators extract characters from ins and convert them to the variable x. The argument to the operator determines the type of x. Extractions are performed only if a call to ipfx(0) returns a nonzero value. Errors are indicated by setting the error state of ins. ios::failbit means that characters in ins did not represent the required type. ios::badbit means that attempts to extract characters failed. ins is always returned. The details of conversion depend on the values of the ins object format state flags and variables, and the type of x. Extractions that use width reset it to 0; otherwise, the extraction operators do not change the value of the istream object format state.

istream &operator >> (char &x)
istream &operator >> (unsigned char &x)

Extracts a character and stores it in x.

istream &operator >> (char *x)
istream &operator >> (unsigned char *x)

Extracts characters and stores them in the array pointed at by x, until a white-space character is found in the iostream object. The action leaves the terminating white-space character in the iostream object. If the iostream object's width() is nonzero, it is taken to be the size of the array and no more than width() --1 characters are extracted. A terminating null character ( '\0' ) is always stored, even if nothing else is done because of the iostream object's error state. The iostream object's width() is reset to 0.

istream &operator >> (short &x)
istream &operator >> (int &x)
istream &operator >> (long &x)
istream &operator >> (unsigned short &x)
istream &operator >> (unsigned int &a Extracts characters and converts them to an integral value according to the conversion specified in the iostream object's format flags. Converted values are stored in x. The first character can be a sign ( - or +). After that, the conversion is octal if ios::oct is set in the iostream object's flags , decimal if ios::dec is set, or hexadecimal if ios::hex is set.

The first nondigit that is left in the iostream object terminates the conversion. If no conversion base flag is set, the conversion proceeds according to C++ lexical conventions: if the first characters (after the optional sign) are 0x or 0X , the conversion is hexadecimal; if the first character is 0 , the conversion is octal; otherwise, the conversion is decimal. If no digits are available (not counting the 0 in 0x or 0X during hex conversion), ios::failbit is set.

istream &operator >> (float &x)
istream &operator >> (double &x)

Extracts characters and converts them according to C++ syntax for a float value or a double value. Converted values are stored in x. If no digits are available in the iostream object, or if the iostream object does not begin with a well formed floating-point or double number, ios::failbit is set.

istream &operator >> (streambuf *b)

Keeps getting characters from ios and inserting them into the buffer b until EOF is reached, if ios::ipfx(0) returns nonzero. Always returns the iostream object.

istream &operator >> (ios &(*f)(ios &))

Calls an ios object manipulator function f for an istream object.

istream &operator >> (istream &(*f)(istream &))

Calls an istream object manipulator function f for an istream object.

Other Member Functions

The unformatted input extractors, get , getline , ignore , and read , are among these functions. Before performing any extractions, these extractors, plus the unformatted function peek (which returns the next character without extracting it), call ipfx(1) and proceed only if a nonzero value is returned.

int gcount()

Returns the number of characters extracted by the last unformatted input function ( get , getline , ignore , and read ). Note that formatted input functions can call unformatted input functions and also reset this number.

int get()

Extracts a character and returns it, or returns EOF if the extraction encounters the end-of-file. It never sets ios::failbit .

istream &get(char &ptr)
istream &get(unsigned char &ptr)

Extracts a single character and stores it in &ptr.

istream &get(char *ptr, int len, char delim)
istream &get(unsigned char *ptr, int len, char delim)

Extracts characters and stores them in the byte array beginning at ptr and extending for len bytes. Extraction stops when any of the following conditions are met:
  • The extractor encounters delim (delim is left in the istream object and not stored.)
  • The istream object has no more characters.
  • The array has only one byte left.

The function stores a terminating null, even if it does not extract any characters because of its error status. The extraction sets ios::failbit only if it reaches an end-of-file before storing any characters.

istream &get(streambuf &sb, char delim)

Extracts characters from an istream object rdbuf() function and stores them into sb. It stops if it encounters the end-of-file, if a store into sb fails, or if it encounters delim (which it leaves in the istream object). The function sets ios::failbit if the extraction stops because the store operation into sb fails.

istream &getline(char *ptr, int len, char delim)
istream &getline(unsigned char *ptr, int len, char delim)

Functions the same as get(char *, int, char) except that these extract a terminating delim character from an istream object. If delim occurs when exactly len characters have been extracted, a filled array is considered to be the cause of the termination and the extraction leaves this delim in the istream object.

istream &ignore(int len, int delim)

Extracts and discards up to len characters. Extraction stops prematurely if delim is extracted or the end-of-file is reached. If delim is EOF , it can never cause termination.

int ipfx(int need)

Returns 0 if the error state of an istream object is nonzero. If necessary (and if it is not null), the function flushes any ios tied to the istream object (see the description of ios::tie() ). Flushing is considered necessary if need is set to 0 or if fewer than need characters are immediately available. If ios::skipws is set in the istream object's flags() function, and need is 0, then the function extracts the leading white-space characters from the istream object. The function returns 0 if an error occurs while skipping white space; otherwise, it returns a nonzero value.

void isfx()

Performs input suffix operations (used for internal processing).

int peek()

Begins by calling ipfx(1) . If that call returns 0, or if the istream object is at the end-of-file, the function returns EOF . Otherwise, it returns the next character without extracting it.

istream &putback(char c)

Tries to back up an istream object rdbuf() function. c must be the character before the get pointer belonging to the istream object rdbuf() . (Unless some other activity is modifying the istream object rdbuf() , this is the last character extracted from the istream object.) If c is not the character before the get pointer, the effect of the function is undefined; the backup may fail and set the error state. The putback function is a member of the istream object, but it never extracts characters so it does not call ipfx . However, it returns without doing anything if the error state is nonzero.

istream &read(char *s, int n)
istream &read(unsigned char *s, int n)

Extracts n characters and stores them in the array begining at s. If it reaches the end-of-file before extracting n characters, the function stores whatever it can extract and sets ios::failbit . To determine the number of characters extracted, use the istream gcount() function.

istream &seekg(streampos)
istream &seekg(streamoff, seek_dir)

Repositions the get pointer of an istream object rdbuf() function.

int sync()

Establishes consistency between internal data structures and the external source of characters. Calls an istream object rdbuf()->sync() , which is a virtual function, so the details depend on the derived class. Returns EOF to indicate errors.

void skipwhite()

Skips extracted white-space characters.

streampos tellg()

Returns the current position of the get pointer of an istream object rdbuf() function.

Examples

#1

char c; 
cin.get(c); 
      

Extracts a single character from cin .

#2

tmp.seekg(10,ios::cur) 
      

Moves the point in a file from which information is read forward 10 bytes.


See Also

ios class
istream_withassign class
istrstream class

istream_withassign class

Adds an assignment operator and a constructor with no operands to the istream class.

Header File

#include <iostream.hxx>

Alternative Header

#include <iostream.h>


Declaration


class istream_withassign: public istream 
{ 
public: 
                        istream_withassign(); 
    virtual             ~istream_withassign(); 
 
    istream_withassign &operator=(istream &); 
    istream_withassign &operator=(streambuf *); 
}; 
 


Description

This class adds an assignment operator and a constructor with no operands to the istream class.

Constructors and Destructors

istream_withassign()

Constructs an istream_withassign object; it does no initialization.

virtual ~istream_withassign()

Deletes an istream_withassign object; no user action is required.

Overloaded Operators

istream_withassign &operator = (istream &s)

Associates an istream object's rdbuf() function with an istream_withassign object and initializes the entire state of that object.

istream_withassign &operator = (streambuf *sb)

Associates sb with an istream_withassign object and initializes the entire state of that object.

istrstream class

Specializes the istream class to perform extractions from arrays of bytes in memory.

Header File

#include <strstream.hxx>

Alternative Header

#include <strstream.h>


Declaration


class istrstream: public istream 
{ 
public: 
                        istrstream(char *); 
                        istrstream(char *, int); 
 
    strstreambuf        *rdbuf(); 
}; 


Description

Objects of this class perform in-core extractions from arrays of bytes in memory.

Constructors and Destructors

istrstream(char *cp)

Constructs an istrstream object and fetches characters from the (null terminated) string cp. The terminating null character does not become part of the sequence. Seeks ( istream::seekg() ) are permitted within the allocated space.

istrstream(char *cp, int len)

Constructs an istrstream object and fetches characters from the array beginning at cp and extending for len bytes. Seeks ( istream::seekg() ) are permitted anywhere within that array.

Member Function

strstreambuf *rdbuf()

Returns the strstreambuf object associated with the istrstream object.

OAPP(TYPE) class

For an ostream object, declares predefined parameterized applicators.

Header File

#include <iomanip.hxx>

Alternative Header

#include <iomanip.h>


Compile-Time Parameter

TYPE---The type of the ostream object. It must be an identifier.

Declaration


class OAPP(TYPE) 
{ 
public: 
    OAPP(TYPE)(ostream &(*f)(ostream &, TYPE)); 
    OMANIP(TYPE) operator()(TYPE a); 
}; 


Constructor

OAPP(TYPE)(ostream &(*f)(ostream &, TYPE))

Creates an applicator.

Operator

OMANIP(TYPE) operator () (TYPE a)

Casts an object of type a into a manipulator function for an ostream object.

See Also

OMANIP(TYPE) class

ofstream class

Supports output to files.

Header File

#include <fstream.hxx>

Alternative Header

#include <fstream.h>


Declaration


class ofstream: public ostream 
{ 
public: 
                 ofstream(); 
                 ofstream(const char *name, int mode = ios::out, 
                         int prot = filebuf::openprot); 
                 ofstream(int fd); 
                 ofstream(int fd, char *p, int len); 
                 ~ofstream(); 
 
    void         attach(int fd); 
    void         close(); 
    void         open(const char *name, int mode = ios::out, 
                         int prot = filebuf::openprot); 
    filebuf      *rdbuf(); 
    void         setbuf(char *p, int len); 
}; 


Description

This class specializes the ostream class to files using a filebuf object to do the output. Your program can perform common operations, such as opening and closing files, without explicitly mentioning filebuf objects.


Constructors and Destructors

ofstream()

Constructs an unopened ofstream object.

ofstream(int fd)

Constructs an ofstream object connected to a file whose descriptor is passed through the fd argument. The file must already be open.

ofstream(int fd, char *p, int len)

Constructs an ofstream object connected to a file whose descriptor is passed through the fd argument, and also initializes the associated filebuf object to use the len bytes starting at p as the reserve area. If p is null or len is 0, the filebuf object is unbuffered.

ofstream(const char *name, int mode, int prot)

Constructs an ofstream object and opens the file specified by the name argument. The mode and prot arguments specify the file open mode and protection. By default, prot is filebuf::openprot . If the open fails, the error state ( io_state ) of the constructed ofstream object indicates failure.

~ofstream()

Deletes an ofstream object.

Member Functions

void attach(int fd)

Connects an ofstream object to a file whose descriptor is passed through the fd argument. A failure occurs when the ifstream object is connected to a file, in which case ios::failbit is set in the ofstream object error state.

void close()

Closes any associated filebuf object and consequently breaks the connection of the ofstream object to the file. The error state of the ofstream object is cleared except on failure. A failure occurs when the call to the filebuf object close() function fails.

void open(const char *name, int mode, int prot)

Opens a file specified by the name argument and connects the ofstream object to it. If the file does not exist, the function tries to create it with the protection specified by the prot argument unless ios::nocreate is set. By default, prot is filebuf::openprot .

Failure occurs if the ofstream object is open or when the call to the filebuf object open() function fails, in which case ios::failbit is set in the filebuf object's error state. The members of open_mode are bits that may be joined together by or (and because this joining takes an int , open() takes an int rather than an open_mode argument). For an explanation of the meanings of these bits in open_mode , see the Enumerated Types section for the ios class.

filebuf *rdbuf()

Returns a pointer to the filebuf object associated with the ofstream object. This function has the same meaning as ios::rdbuf() , but has a different type.

void setbuf(char *p, int len)

Calls the associated filebuf object setbuf() function to request space for a reserve area. A failure occurs if the filebuf object is open or if the call to rdbuf()->setbuf fails for any other reason.

OMANIP(TYPE) class

For an ostream object, declares predefined parameterized manipulators and provides macros for user-defined parameterized manipulators.

Header File

#include <iomanip.hxx>

Alternative Header

#include <iomanip.h>


Compile-Time Parameter

TYPE---The type of the ostream object. It must be an identifier.

Declaration


class OMANIP(TYPE) 
{ 
public: 
    OMANIP(TYPE)(ostream &(*f)(ostream &, TYPE), T a ); 
    friend ostream &operator<<(ostream & s, OMANIP(TYPE) &m); 
}; 


Description

These manipulators serve the ostream class by producing some useful effect, such as embedding a function call in an expression containing a series of insertions and extractions. You also can use manipulators to shorten the long names and sequences of operations required by the ostream class.

In its simplest form, a manipulator takes an ostream& argument, operates on it in some way, and returns it.


Constructor

OMANIP(TYPE)(ostream &(*f)(ostream &, TYPE), T a )

Creates a manipulator.

Operator

ostream &operator << (ostream & s, OMANIP(TYPE) &m)

Sends data to an ostream object.

ostream class

Supports insertion into streambuf objects.

Header File

#include <iostream.hxx>

Alternative Header

#include <iostream.h>


Declaration


class ostream : virtual public ios 
{ 
public: 
                        ostream(streambuf *); 
    virtual             ~ostream(); 
 
    ostream             &flush(); 
    int                 opfx(); 
    void                osfx(); 
    ostream             &put(char c); 
    ostream             &seekp(streampos); 
    ostream             &seekp(streamoff, seek_dir); 
    streampos           tellp(); 
    ostream             &write(const char *ptr, int n); 
    inline ostream      &write(const unsigned char *ptr, int n); 
    ostream             &operator<<(const char *); 
    ostream             &operator<<(char); 
    inline ostream      &operator<<(short); 
    ostream             &operator<<(int); 
    ostream             &operator<<(long); 
    ostream             &operator<<(float); 
    ostream             &operator<<(double); 
    ostream             &operator<<(const unsigned char *); 
    inline ostream      &operator<<(unsigned char); 
    inline ostream      &operator<<(unsigned short); 
    ostream             &operator<<(unsigned int); 
    ostream             &operator<<(unsigned long); 
    ostream             &operator<<(void *); 
    ostream             &operator<<(streambuf *); 
    inline ostream      &operator<<(ostream &(*f)(ostream &)); 
    ostream             &operator<<(ios &(*f)(ios &)); 
 
protected: 
                        ostream(); 
}; 


Description

Objects of this class perform formatted and unformatted insertions into streambuf objects.

Constructors and Destructors

ostream(streambuf *b)

Constructs an istream object. It initializes ios state variables and associates the buffer b with the ostream object.

virtual ~ostream()

Deletes an ostream object.

Overloaded Operators

The following operators are all formatted output inserters. Given the expression outs << x, these operators insert into outs. rdbuf() a sequence of characters representing x. The argument to the operator determines the type of x. Insertions are performed after a call to outs. opfx() only if that call returns nonzero. Errors are indicated by setting the error state of the ostream object. The ostream object is always returned.

Conversion of x to a sequence of characters depends on the type of x and on the values of the ostream object's format state flags and variables. Padding occurs after this representation is determined. If width() is greater than 0, and the representation contains fewer than width() characters, then the function adds enough fill() characters to bring the total number of characters to ios::width() . If ios::left() is set, the sequence is left-adjusted; that is, the function puts the padding after the sequence of characters. If ios::right() is set, the padding is added before the character sequence. If ios::internal() is set, the padding is added after any leading sign or base indication and before the characters that represent the value. ios::width() is reset to 0 but all other format variables are unchanged. The full sequence (padding plus representation) is inserted into the ostream object rdbuf() function.

ostream &operator << (char x)
ostream &operator << (unsigned char x)

Inserts a character x. No special conversion is needed.

ostream &operator << (const char *x)
ostream &operator << (const unsigned char *x)

Inserts a sequence of characters up to (but not including) the terminating null of the string that x points at.

ostream &operator << (short x)
ostream &operator << (int x)
ostream &operator << (long x)
ostream &operator << (unsigned short x)
ostream &operator << (unsigned int x)
ostream &ope Inserts characters as follows:
  • If x is positive, the representation contains a sequence of octal digits if ios::oct is set in the ios object format flags, decimal digits if ios::dec is set, or hexadecimal digits if ios::hex is set. If none of these flags are set, the conversion defaults to decimal.
  • If x is negative, decimal conversion includes a minus sign (--) followed by decimal digits.
  • If x is positive and ios::showpos is set, decimal conversion includes a plus sign (+) followed by decimal digits.
  • Conversions other than decimal treat all values as unsigned.
  • If ios::showbase is set, the hexadecimal representation contains 0x before the hexadecimal digits or 0X if ios::uppercase is set; the octal representation contains a leading 0.

ostream &operator << (float x)
ostream &operator << (double x)

Converts the arguments according to the current values of the ostream object's precision() function, the ostream object's width() function, and the ostream object's format flags: ios::scientific , ios::fixed , and ios::uppercase . The default value for the ostream object's precision() function is 6. If neither ios::scientific nor ios::fixed is set, the value of x determines whether the representation uses scientific or fixed notation.

ostream &operator << (void *v)

Converts pointers to integral values and then converts them to hexadecimal numbers as if ios::showbase was set.

ostream &operator << (streambuf *sb)

Given the expression outs << sb, inserts into sb. rdbuf() the sequence of characters that can be fetched from sb. When no more characters can be fetched from sb, insertion stops. This function does no padding. It always returns the ostream object.

ostream &operator << (ios &(*f)(ios &))

Calls an ios object manipulator function f for an ostream object.

ostream &operator << (ostream &(*f)(ostream &))

Calls an ostream object manipulator function f for an ostream object.

Other Member Functions

ostream &flush()

Calls the ostream object's rdbuf()->sync() function to consume (that is, write to the external file) any characters that may have been stored into a streambuf object but are not yet consumed.

int opfx()

Performs output prefix actions. If the error state of the ostream object is nonzero, it returns immediately. If the value of the ostream object's tie() function is not null, it is flushed. The function returns nonzero except when the error state of the ostream object is nonzero.

void osfx()

Performs output suffix actions before returning from inserters. If ios::unitbuf is set, this function flushes the ostream object. If ios::stdio is set, the function flushes stdout and stderr . It is called by all predefined inserters, and should also be called by user-defined inserters after any direct manipulation of the streambuf object. It is not called by the binary output functions.

ostream &ostream::put(char c)

Inserts c into the ostream object's rdbuf() function. It sets the error state if the insertion fails.

ostream &seekp(streampos)
ostream &seekp(streamoff, seek_dir)

Repositions the put pointer of the ostream object's rdbuf() function.

streampos tellp()

Returns the current position of the put pointer belonging to the ostream object's rdbuf() function.

ostream &write(const char *ptr, int n)
ostream &write(const unsigned char *ptr, int n)

Inserts the n characters starting at ptr into the ostream object's rdbuf() function. These characters may include zeros; that is, ptr need not be a null-terminated string.

Example


char c = 'Z'; 
cout.put(c); 
      

Inserts a single character ( Z ) into cout .


See Also

ostream_withassign class
ostrstream class

ostream_withassign class

Adds an assignment operator and a constructor with no operands to the ostream class.

Header File

#include <iostream.hxx>

Alternative Header

#include <iostream.h>


Declaration


class ostream_withassign: public ostream 
{ 
public: 
                        ostream_withassign(); 
    virtual             ~ostream_withassign(); 
 
    ostream_withassign  &operator=(ostream &); 
    ostream_withassign  &operator=(streambuf *); 
}; 
 


Description

This class adds an assignment operator and a constructor with no operands to the ostream class.

Constructors and Destructors

ostream_withassign()

Constructs an ostream_withassign object; it does no initialization.

virtual ~ostream_withassign()

Deletes an ostream_withassign object; no user action is required.

Overloaded Operators

ostream_withassign &operator = (ostream &s)

Associates s. rdbuf() with the ostream_withassign object and initializes the entire state of that object.

ostream_withassign &operator = (streambuf *sb)

Associates sb with an ostream_withassign object and initializes the entire state of that object.

ostrstream class

Supports the insertion of characters into arrays of bytes in memory.

Header File

#include <strstream.hxx>

Alternative Header

#include <strstream.h>


Declaration


class ostrstream: public ostream 
{ 
 
public: 
                      ostrstream(); 
                      ostrstream(char *, int, int = ios::out); 
                      ~ostrstream(); 
 
     int              pcount(); 
     strstreambuf     *rdbuf(); 
     char             *str(); 
}; 


Description

This class specializes the ostream class for in-core operations by providing members that insert characters into arrays of bytes in memory.

Constructors and Destructors

ostrstream()

Constructs an ostrstream object and dynamically allocates space to hold stored characters.

ostrstream::ostrstream(char *cp, int n, int mode)

Constructs an ostrstream object and stores characters into the array starting at cp and continuing for n bytes. If ios::ate or ios::app is set in mode, the function takes cp to be a null-terminated string and it begins storing at the null character; otherwise, it begins storing at cp. Seeks are allowed anywhere in the array.

~ostrstream()

Deletes an ostrstream object.

Member Functions

int pcount()

Returns the number of bytes that have been stored into the buffer. This function is useful when binary data has been stored and the ostrstream object str() function does not point to a null-terminated string.

strstreambuf *rdbuf()

Returns the strstreambuf associated with the ostrstream object.

char *str()

Returns a pointer to the array being used and freezes the array. After str() has been called, the effect of storing more characters into the strstream object is undefined. If the strstream object was constructed with an explicit array, the function returns a pointer to the array; otherwise, it returns a pointer to a dynamically allocated area. Until str() is called, deleting the dynamically allocated area is the responsibility of the strstream object. After str() returns, dynamic allocation becomes the responsibility of the user program.

Example


char *bptr = bf.str()                                    
      

Initializes the variable bptr with the address of the array associated with the ostrstream object bf . This lets you manipulate the array through bptr just as you would any character array.


SAPP(TYPE) class

Defines parameterized applicators for an ios object.

Header File

#include <iomanip.hxx>

Alternative Header

#include <iomanip.h>


Compile-Time Parameter

TYPE---The type of the ios object. It must be an identifier.

Declaration


class SAPP(TYPE) 
 
{ 
public: 
    SAPP(TYPE)(ios &(*f)(ios &, TYPE)); 
    SMANIP(TYPE) operator()(TYPE a); 
}; 


Constructor

SAPP(TYPE)(ios &(*f)(ios &, TYPE))

Creates an applicator.

Operator

SMANIP(TYPE) operator () (TYPE a)

Casts an object of type a into a manipulator function for an istream or ostream object.

See Also

SMANIP(TYPE) class

SMANIP(TYPE) class

Defines parameterized manipulators for an ios object.

Header File

#include <iomanip.hxx>

Alternative Header

#include <iomanip.h>


Compile-Time Parameter

TYPE---The type of the ios object. It must be an identifier.

Declaration


class SMANIP(TYPE) 
{ 
public: 
    SMANIP(TYPE)(ios &(*f)(ios &, TYPE), TYPE a); 
    friend istream &operator>>(istream &i, SMANIP(TYPE) &m); 
    friend ostream &operator<<(ostream &o, SMANIP(TYPE) &m); 
}; 


Description

These manipulators serve the ios class by producing some useful effect, such as embedding a function call in an expression containing a series of insertions and extractions. You also can use manipulators to shorten the long names and sequences of operations required by the ios class.

In its simplest form, a manipulator takes an ios& argument, operates on it in some way, and returns it.


Constructor

SMANIP(TYPE)(ios &(*f)(ios &, TYPE), TYPE a)

Creates a manipulator.

Operators

ostream &operator << (ostream &o, SMANIP(TYPE) &m)

Sends data to an ostream object.

istream &operator >> (istream &i, SMANIP(TYPE) &m)

Takes data from an istream object.

stdiobuf class

Provides input/output facilities through stdio FILE .

Header File

#include <stdiostream.hxx>

Alternative Header

#include <stdiostream.h>


Declaration


class stdiobuf: public streambuf 
{ 
public: 
                        stdiobuf(FILE *f); 
 
    virtual int         overflow(int = ); 
    virtual streampos   seekoff(streamoff, seek_dir, int mode); 
    FILE                *stdiofile(); 
    virtual int         sync(); 
    virtual int         underflow(); 
}; 


Description

This class specializes the streambuf class for stdio FILE . It uses unbuffered mode causing all operations to be reflected immediately in the stdio FILE .

Constructor

stdiobuf(FILE *f)

Constructs an empty stdiobuf object and connects it to the stdio FILE that the argument f points to.


Member Functions

virtual int overflow(int c)

Called to consume characters. If c is not EOF , this function must also either save c or consume it. Although it can be called at other times, this function is usually called when the put area is full and an attempt is being made to store a new character. The normal action is to consume the characters between pbase() and pptr() , call setp() to establish a new put area, and (if c != EOF ) store c using sputc() . The overflow(c) function should return EOF to indicate an error; otherwise, it should return something else.

virtual streampos seekoff(streamoff off, seek_dir dir, int mode)

Repositions the abstract get and put pointers (not pptr() and gptr() ). mode specifies whether to modify the put pointer ( ios::out bit set), the get pointer, or both ( ios::in bit set). off is interpreted as a byte offset. For the meanings of dir, see the explanation of the enumerated type seek_dir in class ios .

A class derived from streambuf is not required to support repositioning. If the derived class does not, then seekoff() should return EOF . If the derived class does support repositioning, seekoff() should return the new position or EOF on error.

FILE *stdiofile()

Returns a pointer to the stdio FILE associated with the stdiobuf object.

virtual int sync()

Should consume any characters stored into the put area and, if possible, give back to the source any characters in the get area that have not been fetched. When sync() returns, there should be no unconsumed characters and the get area should be empty. If some kind of failure occurs, the function should return EOF .

virtual int underflow()

Called to supply characters for fetching; that is, to create a condition in which the get area is not empty. If this function is called when characters are in the get area, it should return the first character. If the get area is empty, it should create a nonempty get area and return the next character (which it should also leave in the get area). If no more characters are available, underflow() should return EOF and leave an empty get area.

stdiostream class

Specializes the iostream class for stdio FILE .

Header File

#include <stdiostream.hxx>

Alternative Header

#include <stdiostream.h>


Declaration


class stdiostream: public iostream 
{ 
public: 
                stdiostream(FILE *f); 
                ~stdiostream(); 
 
    stdiobuf    *rdbuf(); 
}; 


Description

This class specializes the iostream class for stdio FILE , and causes that class to use a stdiobuf object as its associated streambuf object.

In most other existing implementations, the stdiostream class is derived directly from the ios class rather than from the iostream class. Deriving the stdiostream class from the ios class limits its usefulness and, therefore, can be considered a historical mistake. Nevertheless, for maximum portability, you should use only those stdiostream features that originate from the ios class and avoid the features supplied by the iostream class.


Constructors and Destructors

stdiostream(FILE *f)

Constructs a stdiostream object whose stdiobuf object is associated with the FILE parameter that the f argument points to.

~stdiostream()

Deletes a stdiostream object and closes the associated stdiobuf object.


Member Function

stdiobuf *rdbuf()

Returns a pointer to the stdiobuf object associated with the stdiostream object.

streambuf class

Provides the buffer mechanism for streams.

Header File

#include <iostream.hxx>

Alternative Header

#include <iostream.h>


Declaration


class streambuf 
{ 
public: 
                        streambuf(); 
                        streambuf(char *p, int len); 
    virtual             ~streambuf(); 
    void                dbp(); 
 
protected: 
    int                 allocate(); 
    char                *base(); 
    int                 blen(); 
 
    virtual int  doallocate(); 
 
    char                *eback(); 
    char                *ebuf(); 
    char                *egptr(); 
    char                *epptr(); 
    void                gbump(int n); 
    char                *gptr(); 
    char                *pbase(); 
    void                pbump(int n); 
    char                *pptr(); 
    void                setb(char *b, char *eb, int a = 0); 
    void                setg(char *eb, char *g, char *eg); 
    void                setp(char *p, char *ep); 
    int                 unbuffered(); 
    void                unbuffered(int n); 
 
public: 
    int                 fd(); 
    void                fd(int); 
    FILE                *fp(); 
    void                fp(FILE *); 
    int                 in_avail(); 
    int                 out_waiting(); 
 
    virtual int         overflow(int c = EOF); 
    virtual int         pbackfail(int c); 
 
    int                 sbumpc(); 
 
    virtual streampos   seekpos(streampos, int = ios::in 
                        | ios::out); 
    virtual streampos   seekoff(streamoff, seek_dir, 
                        int = ios::in | ios::out); 
    virtual streambuf   *setbuf(char *ptr, int len); 
 
    streambuf           *setbuf(unsigned char *ptr, int len); 
    streambuf           *setbuf(char *ptr, int len, int i); 
    int                 sgetc(); 
    int                 sgetn(char *ptr, int n); 
    int                 snextc(); 
    int                 sputbackc(char c); 
    int                 sputc(int c = EOF); 
    int                 sputn(const char *s, int n); 
    void                stossc(); 
 
    virtual int         sync(); 
    virtual int         underflow(); 
}; 


Description

This class supports buffers into which you can insert (put) or extract (get) characters. It contains only the basic members for manipulating the characters. Also, several of its member functions are virtual; to implement virtual functions, you typically use a class derived from the streambuf class.

The protected members of the streambuf class present an interface to derived classes organized around the get, put, and reserve areas (arrays of bytes), which are managed cooperatively by the base and derived classes.

The reserve area is a sequence of characters with an associated get pointer, put pointer, or both. This area serves mainly as a resource in which to allocate space for the put and get areas. As characters enter and exit the reserve area, the put and get areas change but the reserve area remains fixed. A collection of character pointer values defines the three areas. These pointers infer a boundary condition; therefore, it may be helpful to consider such pointers as pointing just before the byte, even though they point directly at it.

Classes derived from streambuf vary in their handling of the get and put pointers. The simplest are unidirectional buffers that permit only get and put operations. Such classes serve as producers and consumers of characters. Queue-like buffers (such as strstream and strstreambuf ) have a put and a get pointer that move independently of each other. In such buffers, stored characters are queued until later fetched. File-like buffers (such as filebuf ) allow both get and put operations but have their get and put pointers linked together, so that when one pointer moves so does the other.

You can call virtual functions to manage the collections of characters in the get and put areas. Services supplied by virtual functions include fetching more characters from an ultimate producer and flushing a collection of characters to an ultimate consumer.

If your program expects a buffer to be allocated when none was allocated, then the iostream package allocates a default buffer.


Data Member

void dbp()

Writes directly on file descriptor 1 information in ASCII about the state of the buffer. It is intended for debugging and nothing is specified about the form of the output. What it prints out can be understood only in relation to the protected interface, but dbp() is a public domain function so that it can be called anywhere during debugging.

Constructors and Destructors

streambuf()

Constructs an empty buffer corresponding to an empty sequence.

streambuf(char* base, int length)

Constructs an empty buffer and then sets up the reserve area to be length bytes long starting at base.

virtual ~streambuf()

Deletes the reserve area if one is allocated.


Member Functions

int allocate()

Tries to set up a reserve area. If a reserve area already exists or is unbuffered, it returns 0 without doing anything. If the attempt to allocate space succeeds, allocate() returns 1; otherwise, it returns EOF . No nonvirtual member functions of streambuf call allocate() .

char *base()

Returns a pointer to the first byte of the reserve area. The space between base() and ebuf() is the reserve area.

int blen()

Returns the size, in type char , of the current reserve area.

virtual int doallocate()

In streambuf , it tries to allocate a reserve area using the new operator.

In classes derived from streambuf , this function is called when allocate() determines that space is needed. doallocate() is required to call setb() , to provide a reserve area, or to return EOF if it cannot. It is called only if both unbuffered() and base() are 0.

char *eback()

Returns a pointer to a lower bound on gptr() . The space between eback() and gptr() is available for putback operations.

char *ebuf()

Returns a pointer to the byte after the last byte of the reserve area.

char *egptr()

Returns a pointer to the byte after the last byte of the get area.

char *epptr()

Returns a pointer to the byte after the last byte of the put area.

int fd()

Returns the file descriptor associated with the streambuf object, if any; otherwise, it returns --1.

void fd(int f)

Sets the file descriptor associated with the streambuf object to f.

FILE *fp()

Returns the file pointer associated with the streambuf object, if any; otherwise, it returns 0.

void fp(FILE *f)

Sets the file pointer associated with the streambuf object to f.

void gbump(int n)

Increments gptr() by n, which can be a positive or a negative number. No checks are made on whether the new value of gptr() is in bounds.

char *gptr()

Returns a pointer to the first byte of the get area. The characters available are those between gptr() and egptr() . The next character fetched will be *gptr() unless egptr() is less than or equal to gptr() .

int in_avail()

Returns the number of characters immediately available in the get area for fetching. This number is the number of characters that can be fetched with confidence that an error will not be reported.

int out_waiting()

Returns the number of characters in the put area that have not been consumed (by the ultimate consumer).

virtual int overflow(int c)

In streambuf , this function should be treated as if its behavior is undefined; classes derived from streambuf should always define it.

In classes derived from streambuf , it is called to consume characters. If c is not EOF , overflow(c) also must either save c or consume it. Although it can be called at other times, this function is usually called when the put area is full and an attempt is being made to store a new character. The normal action is to consume the characters between pbase() and pptr() , call setp() to establish a new put area, and (if c != EOF ) store c using sputc() . overflow(c) should return EOF to indicate an error; otherwise, it should return something else.

virtual int pbackfail(int c)

In streambuf , this function always returns EOF .

In classes derived from streambuf , this function is called when eback() equals gptr() and an attempt has been made to put c back. If this situation can be managed (for example, by repositioning an external file), pbackfail(c) should return c; otherwise, it should return EOF .

char *pbase()

Returns a pointer to the put area base. Characters between pbase() and pptr() are stored into the buffer but are not yet consumed.

void pbump(int n)

Increments pptr() by n, which can be positive or negative. No checks are made on whether the new value of pptr() is in bounds.

char *pptr()

Returns a pointer to the first byte of the put area. The space between pptr() and epptr() is the put area.

int sbumpc()

Moves the get pointer forward one character and returns the character it moved past. The function returns EOF if the get pointer is currently at the end of the sequence.

virtual streampos seekoff(streamoff off, (ios::)seek_dir dir, int mode)

In streambuf , this function returns EOF .

In classes derived from streambuf , it repositions the abstract get and put pointers (not pptr() and gptr() ). mode specifies whether to modify the put pointer ( ios::out bit set) or the get pointer ( ios::in bit set) or both pointers. off is interpreted as a byte offset (it is a signed value). For the meanings of dir, see the explanation of the enumerated type seek_dir in class ios .

A class derived from streambuf is not required to support repositioning. If the derived class does not, then seekoff() should return EOF . If the derived class does support repositioning, seekoff() should return the new position or EOF on error.

virtual streampos seekpos(streampos pos, int mode)

In streambuf , this function returns seekoff(streamoff(pos), ios::beg, mode) . To define seeking in a derived class, you can often define seekoff() and use the inherited streambuf::seekpos .

In classes derived from streambuf , this function repositions the streambuf get pointer, put pointer, or both, to pos. mode specifies the affected pointers. seekpos() returns the argument pos or EOF if the class does not support repositioning or if an error occurs. streampos(0) signifies the beginning of the file; streampos(EOF) indicates an error.

void setb(char *b, char *eb, int a)

Sets base() to b and ebuf() to eb. The a argument controls whether the reserve area will be subject to automatic deletion. If a is nonzero, then b will be deleted when base() is changed by another call to setb() , or when the destructor is called for the streambuf object. If b and eb are both null, then the reserve area effectively does not exist. If b is nonnull, a reserve area exists even if eb is less than b (in which case the reserve area has 0 length).

virtual streambuf *setbuf(char *ptr, int len)
streambuf *setbuf(unsigned char *ptr, int len)

In streambuf , this function honors the request for a reserve area if there is none.

In classes derived from streambuf , this function offers for use as a reserve area the array at ptr with len bytes. Normally, if ptr or len is 0, the action is interpreted as a request to make the streambuf object unbuffered. The derived class has the choice of using or not using this area by accepting or ignoring the request. setbuf() should return a reference to the streambuf object if the derived class honors the request; otherwise, it should return 0.

streambuf *setbuf(char *ptr, int len, int i)

Offers the len bytes starting at ptr as the reserve area. If ptr is null, or len is 0 or negative, then the function requests an unbuffered state. Whether the offered area is used or a request for an unbuffered state is honored depends on details of the derived class. setbuf() normally returns a reference to the streambuf object, but if the derived class does not accept the offer or honor the request, setbuf() returns 0.

void setg(char *eb, char *g, char *eg)

Sets eback() to eb, gptr() to g, and egptr() to eg.

void setp(char *p, char *ep)

Sets base() and pptr() to p and epptr() to ep.

int sgetc()

Returns the character after the get pointer; it does not move the get pointer. It returns EOF if no character is available.

int sgetn(char *ptr, int n)

Fetches n characters following the get pointer and copies them to the area starting at ptr. If fewer than n characters occur before the end of the sequence, sgetn() fetches the characters that remain. It repositions the get pointer after the fetched characters and returns the number of characters fetched.

int snextc()

Moves the get pointer forward one character and returns the character after the new position. If the pointer is at the end of the sequence, either before or after moving forward, the function returns EOF .

int sputbackc(char c)

Moves the get pointer back one character. c must be the current content of the sequence just before the get pointer. The underlying mechanism may back up the get pointer or may rearrange its internal data structures so that c is saved. The effect is undefined if c is not the character before the get pointer. The function returns EOF , by calling pbackfail() , when it fails. The conditions under which it can fail depend on the details of the derived class.

int sputc(int c)

Stores c after the put pointer and moves the put pointer past the stored character (usually this extends the sequence). The function returns EOF when an error occurs. Conditions that can cause errors depend on the derived class.

int sputn(const char *s, int n)

Stores after the put pointer the n characters starting at s, and moves the put pointer past them. It returns the number of characters successfully stored. Normally n characters are successfully stored, but fewer characters may be stored when errors occur.

void stossc()

Moves the get pointer ahead one character. If the pointer started at the end of the sequence, stossc() has no effect.

virtual int sync()

In streambuf this function returns 0 if the get area is empty and no unconsumed characters are present; otherwise, it returns EOF .

In classes derived from streambuf , this function is called to let derived classes examine the state of the put, get, and reserve areas, and to synchronize these areas with any external representation. Normally sync() should consume any characters stored into the put area and, if possible, give back to the source any characters in the get area that have not been fetched. When sync() returns, no unconsumed characters should remain and the get area should be empty. If some kind of failure occurs, sync() should return EOF .

int unbuffered()

Returns the current buffering state flag, which is independent of the actual allocation of a reserve area. This function's primary purpose is to find out if a reserve area is being allocated automatically by allocate() .

void unbuffered(int n)

Sets the value of the current buffering state flag. If n equals 0, then the streambuf object is buffered; otherwise it is unbuffered. This function's primary purpose is to control whether a reserve area is allocated automatically by allocate() .

virtual int underflow()

In streambuf , this function should be treated as if its behavior is undefined; classes derived from streambuf must define it.

In classes derived from streambuf , it is called to supply characters for fetching; that is, to create a condition in which the get area is not empty. If this function is called when characters are in the get area, it should return the first character. If the get area is empty, it should create a nonempty get area and return the next character (which it should also leave in the get area). If no more characters are available, underflow() should return EOF and leave an empty get area.


Example


static const int bufsize = 1024; 
char buf[bufsize] ;   
int p, g ; 
do {                   
        in->sgetc() ; (1)
        g = in->in_avail() ;  (2)
        if (g > bufsize) g = bufsize ;  (3)
        g = in->sgetn(buf,g) ; 
        p = out->sput(buf,g) ; 
        out->sync() ;  (4)
        if (p!=g) error("output error"); 
        } while (g > 0) 
      

Provides a way to pass characters into the in and out arrays as soon as the characters become available (as when someone types them from a terminal) as follows:

  1. Ensures at least one character is immediately available in the in array (unless the get pointer is at the end of the sequence).
  2. Returns the number of characters immediately available.
  3. Checks that chunks in which the characters become available are less than bufsize , and that they fit into the arrays.
  4. Sends characters put into the out array to the ultimate consumer.

strstream class

Specializes the iostream class for storing in and fetching from arrays of bytes.

Header File

#include <strstream.hxx>

Alternative Header

#include <strstream.h>


Declaration


class strstream: public iostream 
{ 
public: 
                     strstream(); 
                     strstream(char *, int, int); 
 
    strstreambuf     *rdbuf(); 
    char             *str(); 
}; 


Description

This class specializes the iostream class for storing in and fetching from arrays of bytes. It handles all predefined data types, and provides an extensive set of options for performing input and output on these data types.

Constructors and Destructors

strstream()

Constructs an strstream object and dynamically allocates space to hold stored characters.

strstream(char *cp, int n, int mode)

Constructs an strstream object. It stores characters into the array starting at cp and continuing for n bytes. If ios::ate or ios::app is set in mode, cp is presumed to be a null-terminated string and storing begins at the null character; otherwise, storing begins at cp. Seeks are permitted anywhere in the array.

Member Functions

strstreambuf *rdbuf()

Returns a pointer to the strstreambuf object associated with a strstream object.

char *str()

Returns a pointer to an explicit array, to be used as the associated strstreambuf object, if the strstream object was constructed with such an array; otherwise, it returns a pointer to a dynamically allocated area. Until str() is called, deleting the dynamically allocated area is the responsibility of the strstream object. After str() returns, dynamic allocation becomes the responsibility of the user program. After str() has been called, the effect of storing more characters into the strstream object is undefined.

strstreambuf class

Specializes the streambuf class for input and output performed on arrays of bytes in memory.

Header File

#include <strstream.hxx>

Alternative Header

#include <strstream.h>


Declaration


class strstreambuf: public streambuf 
{ 
public: 
                        strstreambuf(); 
                        strstreambuf(char *, int, char *); 
                        strstreambuf(int); 
                        strstreambuf(unsigned char *, int, 
                        unsigned char *); 
                        strstreambuf(void *(*a)(long), 
                        void (*f)(void *)); 
 
    void                freeze(int n = 1); 
    virtual int         overflow(int); 
    virtual streambuf   *setbuf(char *, int); 
    char                *str(); 
    virtual int         underflow(); 
};         


Description

Objects of this class let you use an array of bytes (a string of characters) in memory as a streambuf object for stream input/output operations on various kinds of data. Mapping between abstract get and put pointers and char * pointers is direct in the sense that a char * is interpreted as logically pointing immediately ahead of the char it actually points to. Moving the pointers corresponds to incrementing and decrementing the char * values.

To accommodate the need for strings of arbitrary length, this class supports a dynamic mode. When a strstreambuf object is in dynamic mode, space for the character is allocated as needed. When the sequence is extended too far, it is copied to a new array.

If your program expects a buffer to be allocated when none was allocated, then the iostream package allocates a default buffer, with a length specified by BUFSIZ as defined in stdio.h . The package then issues the following warning:


Warning; a null pointer to streambuf was passed to ios::init() 


Constructors and Destructors

strstreambuf()

Constructs an empty strstreambuf object in dynamic mode. This means that space is automatically allocated to accommodate characters put into the strstreambuf object (using the new and delete operators). Because this may require copying the original characters, programs that have many characters to insert should use setbuf() to inform the strstreambuf object about the needed allocation of space, or to use one of the constructors that follow.

strstreambuf(int n)

Constructs an empty strstreambuf object in dynamic mode. The initial allocation of space is at least n bytes.

strstreambuf(char *ptr, int n, char *pstart)
strstreambuf(unsigned char *ptr, int n, unsigned char *pstart)

Constructs a strstreambuf object to use the bytes starting at ptr. The strstreambuf object is in static mode; it does not grow dynamically. If n is positive, then the n bytes starting at ptr are used as the strstreambuf object. If n is 0, ptr is presumed to point to the beginning of a null-terminated string and the bytes of that string (not including the terminating null character) constitute the strstreambuf object. If n is negative, then the strstreambuf object is presumed to continue indefinitely.

The get pointer is initialized to ptr. The put pointer is initialized to pstart. If pstart is not null, then the initial sequence for fetching (the get area) consists of the bytes between ptr and pstart. If pstart is null, then storing operations are treated as errors and the initial get area consists of the entire array.

strstreambuf(void *(*a)(long n), void (*f)(void *ptr))

Constructs an empty strstreambuf object in dynamic mode. a is used as the allocator function in dynamic mode. The argument passed to a is a long denoting the number of bytes to be allocated. If the a argument is null, the new operator is used. f is used to free (or delete) get, put, or reserve areas returned by a. The argument to f becomes a pointer to the array allocated by a. If f is null, the delete operator is used.


Member Functions

void freeze(int n)

Inhibits (freezes) automatic deletion of the current array if n is nonzero, or permits (unfreezes) automatic deletion if n is 0. Deletion normally occurs when more space is needed, or when the strstreambuf object is being destroyed. Only space obtained through dynamic allocation is free. Storing characters into a strstreambuf that was dynamically allocated and is now frozen causes an error (the effect is undefined). If you want to resume storing characters in such a strstreambuf object you can thaw (unfreeze) it.

virtual int overflow(int c)

In classes derived from streambuf , it is called to consume characters. If c is not EOF , overflow(c) also must either save c or consume it. Although it can be called at other times, this function is usually called when the put area is full and an attempt is being made to store a new character. The normal action is to consume the characters between pbase() and pptr() , call setp() to establish a new put area, and (if c != EOF ) store c using sputc() . overflow(c) should return EOF to indicate an error; otherwise, it should return something else.

virtual streambuf *setbuf(char *ptr, int n)

Causes the strstreambuf object to remember n (if ptr is 0); this ensures that at least n bytes are allocated during the next dynamic mode allocation.

char *str()

Returns a pointer to the first character in the current array and freezes the strstreambuf object. If the strstreambuf object was constructed with an explicit array, the function returns a pointer to that array. If the strstreambuf object is in dynamic allocation mode but nothing has been restored yet, the returned pointer is null.

virtual int underflow()

In classes derived from streambuf , it is called to supply characters for fetching; that is, to create a condition in which the get area is not empty. If this function is called when characters are in the get area, it should return the first character. If the get area is empty, it should create a nonempty get area and return the next character (which it should also leave in the get area). If no more characters are available, underflow() should return EOF and leave an empty get area.


Previous Next Contents Index

Privacy statement Using this site means you accept its terms
© 2005 Hewlett-Packard Development Company, L.P.