IOS(3C++)

NAME
ios - basic iostreams formatting

SYNOPSIS

#include <iostream.h>

class unsafe_ios {
public:
	// exported types
	// stream status bits
        enum io_state   {
            goodbit  = 0x00,        // no bit set: all is ok
            eofbit   = 0x01,        // at end of file
            failbit  = 0x02,        // last I/O operation failed
            badbit   = 0x04,        // invalid operation attempted
            hardfail = 0x80         // unrecoverable error
            };
	// stream operation mode
        enum open_mode  {
            in       = 0x01,        // open for reading
            out      = 0x02,        // open for writing
            ate      = 0x04,        // seek to eof upon original open
            app      = 0x08,        // append mode: all additions at eof
            trunc    = 0x10,        // truncate file if already exists
            nocreate = 0x20,        // open fails if file doesn't exist
            noreplace= 0x40         // open fails if file already exists
        };
	// stream seek direction
        enum seek_dir { beg=0, cur=1, end=2 };

        // formatting flags
        enum    {
            skipws    = 0x0001,     // skip whitespace on input
            left      = 0x0002,     // left-adjust output
            right     = 0x0004,     // right-adjust output
            internal  = 0x0008,     // padding after sign or base indicator
            dec       = 0x0010,     // decimal conversion
            oct       = 0x0020,     // octal conversion
            hex       = 0x0040,     // hexidecimal conversion
            showbase  = 0x0080,     // use base indicator on output
            showpoint = 0x0100,     // force decimal point (floating output)
            uppercase = 0x0200,     // upper-case hex output
            showpos   = 0x0400,     // add '+' to positive integers
            scientific= 0x0800,     // use 1.2345E2 floating notation
            fixed     = 0x1000,     // use 123.45 floating notation
            unitbuf   = 0x2000,     // flush all streams after insertion
            stdio     = 0x4000      // flush stdout, stderr after insertion
            };
public:
	// exported functions

	// format-related functions
	long	flags();
	long	flags(long bits);
	long	setf(long setbits, long field);
	long	setf(long setbits);
	long	unsetf(long unsetbits);
	int	width();
	int	width(int len);
	char	fill();
	char	fill(char ch);
	int	precision(int len);
	int	precision();
	int     skip(int doskip); // obsolete

	// state-related functions
	int	rdstate();
	int	eof();
	int	fail();
	int	bad();
	int	good();
	void	clear(int state=0);

	// other functions
	ostream* tie(ostream* tiedstream);
	ostream* tie();
	streambuf* rdbuf();
	static	long	bitalloc();
	static	int	xalloc();
	long &	iword(int index);
	void* &	pword(int index);
	static	void	sync_with_stdio();
public:
	// exported operator and conversion functions
		operator void* ();
	int	operator ! ();
public:
	// exported constructor, destructor
	unsafe_ios(streambuf* sbp);
	virtual ~unsafe_ios();
public:
	// exported data members
	static	const long basefield;	// dec | oct | hex
	static	const long adjustfield;	// left | right | internal
	static	const long floatfield;	// scientific | fixed

protected:
	// protected function
	void	init(streambuf* sbp);
	// protected constructor
	unsafe_ios();
	void setstate (int);
	static void (*stdioflush)();

private:
	// private members to prevent copying
	unsafe_ios(unsafe_ios&);
	void	operator= (unsafe_ios&);
};
class ios : virtual public unsafe_ios, public stream_MT {
public:
	// format-related functions
	long		flags();
	long		flags(long);
	long		setf(long setbits, long field);
	long		setf(long);
	long		unsetf(long);
	int		width();
	int		width(int);
	char		fill();
	char		fill(char);
	int		precision();
	int		precision(int);

	// state-related functions
	int		rdstate();
	int		eof();
	int		fail();
	int		bad();
	int		good();
	void		clear(int state =0);

	// other functions
	ostream*	tie();
	ostream*	tie(ostream*);
	streambuf*	rdbuf();
	static long	bitalloc();
	static int	xalloc();
	long&		iword(int);
	void* &		pword(int);
	static void	sync_with_stdio();
public:
	// exported operator and conversion functions
			operator void*();
	int		operator!();
public:
	// exported operator and conversion functions
			ios(streambuf* sbp);
			virtual ~ios();
protected:
			init(streambuf* sbp);
			ios();
			setstate(int);
	static void	(*stdioflush)();
protected:
	static	stream_rmutex static_mutlock;
	static int 	mutex_init_count;
private:
			ios(ios&);
	void		operator=(ios&) ;
};

// Predefined manipulators
unsafe_ostream& endl(unsafe_ostream&);
unsafe_ostream& ends(unsafe_ostream&);
unsafe_ostream& flush(unsafe_ostream&);
ostream& endl(ostream&);
ostream& ends(ostream&);
ostream& flush(ostream&);
unsafe_ios& dec(unsafe_ios&);
unsafe_ios& hex(unsafe_ios&);
unsafe_ios& oct(unsafe_ios&);
ios& dec(ios&);
ios& hex(ios&);
ios& oct(ios&);
unsafe_istream& ws(unsafe_istream&);
istream& ws(istream&);

DESCRIPTION
Class ios is a virtual base class of all stream objects. It provides the basic state and formatting data for a stream. Several enumerations are defined, and a large collection of functions. These are described below.

Class unsafe_ios implements all of the functionality of this class. Class ios is a "wrapper" class that implements mutex locks around each of the member functions of unsafe_ios to protect against access by multiple threads. Use of the protected class does not guarantee mt-safety, however; for more information on making your application mt-safe, see the C++ 4.1 Library Reference Manual, Chapter 5, "Using libC in a Multithreaded Environment."

  ENVIRONMENT
The discussion about thread safety applies only to Solaris 2.x. On Solaris 1.x the ``safe'' and ``unsafe'' functions behave identically.

  Enumerations

io_state
    Member functions use these enumerations to keep track of the error state of the stream. See also the ``Error States'' section below for how to test these bits. io_state is really a collection of bits, as follows:
    goodbit
    This ``bit'' is really the absence of any error bits, and indicates that the stream is in a good state.
    eofbit
    This bit is normally set when end of file has been reached during an extraction. It is not set as the result of a succesful extraction reaching end of file, but when end of file is reached while attempting further extractions. ``End of file'' in this sense is an abstraction as defined by the streambuf associated with the stream. Normally this bit is not set for output streams.
    failbit
    This bit is set when an attempted extraction or conversion has failed, usually due to unexpected characters. Further attempted extractions will fail until this bit is cleared, to prevent running on after improper input. Usually the stream is still usable, and extraction may be continued after clearing the bit and dealing with the unexpected input.
    badbit
    This bit indicates that some operation on the associated streambuf has failed. Typically, attempting further operations will not succeed, even after clearing the bit. Example situations would be an output error, or immediate end of file on an attempted input operation.
    hardfail
    This bit is reserved to the implementation to indicate that the stream cannot be further used. Typically it represents a hardware failure of some kind. The bit cannot be cleared by any publicly-accessible function.

open_mode
    These enumerations are described in fstream(3C++), under the description of function open().

seek_dir
    These enumerations are described in sbufpub(3C++), under the description of function seekoff().

formatting flags
    Member functions use these enumerations of anonymous type to control input and output formatting. See the "Format Control" section below.

  Constructors and Assignment

ios(sbp)
    The streambuf pointed to by sbp becomes the streambuf associated with the ios being constructed. The pointer must not be null.

ios() // protected
    init(sbp) // protected
    Historically, a virtual base class required a default constructor (one with no arguments), because there used to be no way to pass arguments to a constructor for a virtual base class. Class ios therefore has a default constructor and a separate intialization function taking a pointer to a streambuf. A derived class uses the protected constructor ios() by default, and calls initialization function init(streambuf*). The argument to init points to the streambuf to be associated with the ios being constructed, and must not be null. Example:
    class istream : virtual public ios { ... };
    istream::istream(streambuf* s)
    {
        ios::init(s);
        // ...
    }

ios(iosref) // private
    stream2=stream1 // private
    The copy constructor and assignment operator are private to prevent copying of ios objects, since the effect of such copying is not well defined. Usually you want to copy a pointer to the object, or pass a reference to a function.

  Error States

Several functions enable testing and adjusting the error state bits, as follows.

int i = s.rdstate()
    Returns the error state bits of stream s as an int.

s.clear(state)
    Stores its int parameter as the error state of stream s. The value of state should be derived only from the return of rdstate and/or combinations of the io_state bits. To clear only one bit in the stream state, use something like s.clear(~ios::failbit & s.rdstate());

int i = s.good()
    Returns non-zero if the error state is good; that is, if no bits are set. Otherwise, returns zero. In particular, returns zero if eofbit is set.

int i = s.eof()
    Returns non-zero if the eofbit is set, zero otherwise.

int i = s.fail()
    Returns non-zero if any of failbit, badbit, or hardfail is set, zero otherwise.

int i = s.bad()
    Returns non-zero if either of badbit or hardfail is set, zero otherwise.

  Other Status Testing

It is often convenient to be able to test the state of a stream directly. Since typical insertion and extraction operators return a reference to the stream, you can test the return values of the operations. Two operators are defined to permit this testing.

operator void* ()
    You may use an explict cast of a stream to void*, or use a stream in a boolean context to test its state. The result is 0 if any of failbit, badbit, or hardfail is set. The result is a non-zero pointer if the stream is in a good or eof state. Examples:
    if( cout ) ...		// next output will probably succeed
    if( cin >> x ) ...		// input to x succeeded

operator ! ()
    This operator provides the inverse of the above testing. The result is non-zero if any of failbit, badbit, or hardfail is set, zero otherwise. Examples:
    if( ! cout ) ...		// output will not succeed
    if( ! (cin >> x) ) ...	// input to x failed

  Format Control

A ios maintains a format state which is controlled by formatting flags, and the three functions fill(), width(), and precision(). The formatting flags are a collection of bits described below, declared as enumerations of an anonymous type. These format state bits are kept in a long int and may be manipulated independently via two versions of the flags() function.

The formatting flags may be set and cleared independent of other operations. They change only by explicit programmer action. The flags are as follows:

skipws
    If this flag is set, formatted extractors will skip leading whitespace; otherwise, leading whitespace is not skipped. This flag is set by default, allowing free-format input text. Unformatted extractors do not examine this flag.

left
    right
    internal
    These flags control how padding is inserted during formatted operations. At most one of these three flags may be set at one time. The three flags may be addressed as a unit by the static member ios::adjustfield. If left is set, the value is left-adjusted in its field width, meaning that padding is added on the right. If right is set, the value is right-adjusted in its field width, meaning that padding is added on the left. If internal is set, padding is added after any leading base or sign field, and before the value. The default (none of the flags set) is right. The fill character used for padding defaults to the space character, and may be set with the fill function. The amount of padding is determined by the field width as set by the width function. See also manip(3C++).

dec
    oct
    hex
    These flags control the conversion base of integer data. At most one of these three flags may be set at one time. The three flags may be addressed as a unit by the static member ios::basefield. Conversions are done in decimal (base 10) if dec is set, in octal (base 8) if oct is set, or in hexadecimal (base 16) if hex is set. If none of the flags is set, insertions are done in decimal, and extractions are converted according to the C++ rules for representing integer constants. That is, a leading ``0x'' or ``0X'' will result in hex conversion, a leading `0' will result in octal conversion, and a leading `1' through `9' will result in decimal conversion for extraction. The default is none of these bits set. The manipulators dec, oct, and hex may also be used to set the conversion base as described below in section ``Predefined Manipulators''.

showbase
    If this flag is set, insertions of converted integral values will be in the form used for representing C++ integer constants. That is, octal values will begin with a leading `0', and hexadecimal values will begin with a leading ``0x'' or ``0X''. (See ``uppercase'' below.) The default is unset.

showpos
    If this flag is set, a plus sign (`+') will be added to insertions of converted positive decimal values (including floating-point). The default is unset.

uppercase
    If this flag is set, an uppercase `X' will be used in insertions of converted hexidecimal values when showbase is set, and an uppercase `E' will be used for floating-point conversions. Otherwise, lowercase `x' and `e' will be used, respectively. The default is unset.

fixed
    scientific
    These flags control the type of conversion used when floating-point values are converted for insertion. The two flags may be addressed as a unit by the static member ios::floatfield. The rules followed for conversion are generally the same as for the C stdio function printf. (See printf(3V).) If scientific is set, `e' format is used. If fixed is set, `f' format is used. If neither is set, `g' format is used. (See also uppercase above.) The value set by width, if any, is used as the printf field width specification. The value set by precision, if any, is used as the printf precision specification.

showpoint
    If this flag is set, trailing zeros, or a trailing decimal point, will appear in the conversion of floating-point values. The default is to truncate trailing zeros or a trailing decimal point.

unitbuf
    If an output stream is buffered, the buffer is flushed when it fills, or when it is explicitly flushed. This can result in delayed output, or lost output if the program should crash. A stream may be unbuffered, eliminating delays and lost output, but at the cost of a system call per character output. If the unitbuf is set, the buffer will be flushed after each complete insertion. Unit buffering is thus a compromise, providing frequent output at lower cost than unbuffered output, and not requiring extra flush calls in the program source. In particular, unit buffering may be turned on and off at selected places in the code without changing any other source code. By default, this flag is not set.

stdio
    This flag causes the C stdio files stdout and stderr to be flushed after each insertion in the stream. This may be useful when C stdio on the standard files is mixed with iostreams on other files. By default, this flag is not set.

The format control functions are as follows:

long theflags = s.flags()
    Returns the current formatting flags of stream s in a long.

long oldflags = s.flags(newflags)
    Uses the long value of newflags to replace all the formatting flags in stream s. Returns the previous formatting flags in a long.

long oldflags = s.setf(newflags)
    Each bit which is set in the long value newflags is set in the formatting flags of stream s. The remaining formatting flags are unaffected. Returns the previous formatting flags in a long. Note the flags function replaces all the flag bits, while the setf function sets just those bits which are specified. This version of setf is most useful for setting a flag which is not part of a group. See the second form of this function below for setting one of a group of flags.

long oldflags = s.setf(newflags, field)
    The bits which are set in the long value field mark the formatting flags which are replaced by the corresponding bits in the long value newflags. Returns the previous value of the designated flags. Typically, one of the constants basefield, adjustfield, or floatfield is used as the value of field. Example - set to left-justification, output a value, and restore the previous justification:
    long oldadjust = cout.setf(ios::left, ios::adjustfield);
    cout << data;
    cout.setf(oldadjust, ios::adjustfield);
    This technique ensures that only one of the adjustfield bits is ever set, and allows convenient restoration of the previous status. Using zero for the new value of the field will clear just those flags. Example - clear the integer conversion base to the default state:
    cout.setf(0, ios::basefield);
    See also the manipulators setiosflags and resetiosflags in manip(3C++).

long oldflags = s.unsetf(newflags)
    Each bit which is set in the long value newflags is unset in the formatting flags of stream s. The remaining formatting flags are unaffected. Returns the previous formatting flags in a long. Note the setf function sets corresponding flag bits, while the unsetf function clears them. See also the manipulator resetiosflags in manip(3C++).

char thefill = s.fill()
    Returns the current fill character of stream s. The fill character is used for padding an insertion to the designated field width. This release supports only single-byte characters for fill. See the discussion above for left, right, and internal.

char oldfill = s.fill(newfill)
    Sets the fill character of stream s to newfill and returns the old fill character. The default fill character is the space. See also the manipulator setfill in manip(3C++).

int theprec = s.precision()
    Returns the current ``precision'' format state of stream s. It controls the number of significant digits converted in floating-point insertions. See the discussion above for scientific and fixed.

int oldprec = s.precision(newprec)
    Sets the ``precision'' format state of stream s to newprec, and returns the old value. The default value is 6. See also the manipulator setprecision in manip(3C++).

int thewidth = s.width()
    Returns the current ``field width'' format state of stream s. If the field width is zero, inserters will insert only the characters necessary to represent the value being inserted. If the field width is greater than the number of characters needed, the field will be padded with the fill character to the specified width, as described above. If the field width is less than the number of characters needed, the width will be extended. The field width represents the minimum field width; it cannot be used to provide truncation to a maximum field width. For wide character output the width is still measured in characters, not in bytes.

int oldwidth = s.width(newwidth)
    Sets the ``field width'' format state of stream s to newwidth, and returns the old value. The default value is 0. The field width is reset to zero automatically after every formatted insertion or extraction. It must therefore be reset for each operation requiring a field width. See also the manipulator setw in manip(3C++).

  User-defined Format Flags

User-defined format flags and variables are provided for derived classes which may need their own. Once allocated for a class, the flags and variables are reserved for the duration of the program; several independent classes may allocate their own flags and variables without conflict.

long thebit = ios::bitalloc()
    This static member function returns a long with one previously unallocated flag bit set. This value may then be used as a flag, for example, in calls to setf, for class-specific purposes. At least 16 bits are available for allocation. When no bits are available, this function returns zero.

int index = ios::xalloc()
    This static member function returns a previously unused index into an array of words. A word is big enough to contain a long or a void*. This index may then be used with functions iword or ipword to get a reference to a reserved status variable.

long theword = s.iword(i)
    void* theptr = s.ipword(i)
    When i is an index value returned by a call to ios::xalloc, these functions return a reference to the ith user-defined status variable (word) for class s. Function iword returns the reference typed as a long, and function ipword returns the reference typed as a void*. Note: Do not depend on the returned reference being stable for an indefinite period. In particular, any call to xalloc() may invalidate a previous reference.

  Miscellaneous Functions

streambuf* sbp = s.rdbuf()
    Returns a pointer to the streambuf associated with the stream. This is part of the construction of a stream, and the buffer class object is not normally changed. This function may be used to get at streambuf functions directly, given a stream object.

ostream* oldosp = s.tie(osp)
    A stream may be ``tied'' to one ostream, kept track of by the ``tie'' stream variable. Whenever a stream needs to acquire more input or flush its output, the tied stream, if any, is flushed first. For example, cin is initially tied to cout, so that pending output, such as a prompt, will be flushed before new input is attempted. This function sets the tie variable of stream s to the ostream pointed to by input parameter osp, and returns the old value of the tie variable. The sequence
    ostream* oldosp = s.tie(0);
    ... do something ...
    s.tie(oldosp);
    will untie a stream while some work is done, then restore the previous tie.

ostream* theosp = s.tie()
    Returns the current value of the ``tie'' variable. (See above.)

ios::sync_with_stdio()
    If C stdio and C++ stream operations are performed on the same standard file, synchronization problems will occur. Since each style of I/O will have its own buffering, I/O will not occur in the order of program execution. To solve this synchronization problem, call this static function prior to doing any I/O to any of the standard streams cin, cout, cerr, or clog. This function resets the standard streams to use stdiobufs. I/O via stdio and streams will then be synchronized. There is a substantial performance degradation compared to using just buffered stream I/O or just buffered stdio. See stdiobuf(3C++). Note: sync_with_stdio is needed only when doing I/O to the same standard input, output, or error file. You may use exclusively stdio input functions on stdin and exclusively stream output functions on cout with no difficulty.

  Predefined Manipulators

A manipulator may be used apparently as an inserted or extracted object, but really only changes the state of the stream. See manip(3C++) for more information. Several manipulators are predefined for use with streams.

s >> dec
    s << dec
    These set the conversion base of stream s to 10.

s >> oct
    s << oct
    These set the conversion base of stream s to 8.

s >> hex
    s << hex
    These set the conversion base of stream s to 16.

s >> ws
    This extracts and discards whitespace from stream s. See istream(3C++).

s << endl
    Inserts a newline into stream s and flushes the stream. See ostream(3C++).

s << ends
    Inserts a null character (`\0') into stream s to end the string. See strstream(3C++).

s << flush
    Flushes the stream s. See ostream(3C++).

Additional manipulators become available when you include <manip.h>. See manip(3C++)

SEE ALSO

ios.intro(3C++), filebuf(3C++), fstream(3C++), istream(3C++), manip(3C++), ostream(3C++), printf(3V) sbufprot(3C++), sbufpub(3C++), ssbuf(3C++), stdiobuf(3C++), strstream(3C++), stream_locker(3C++), stream_MT(3C++),

C++ 4.1 Library Reference Manual:

Chapter 4, "The Iostream Library",

Chapter 5, "Using libC in a Multithreaded Environment."