13.27 <ios>

The <ios> header declares the classes, types, and manipulator functions that form the foundation of the C++ I/O library (which is often called I/O streams). The class ios_base is the base class for all I/O stream classes. The class template basic_ios derives from ios_base and declares the behavior that is common to all I/O streams (e.g., establishing a stream buffer and defining the I/O state).

Refer to Chapter 9 for more information about input and output, including the use of manipulators, formatting flags, streams, and stream buffers.

The <ios> header #includes <iosfwd>.

basic_ios class template Base class template for all I/O streams

template <class charT, class traits = char_traits<charT> >

class basic_ios : public ios_base

{

public:

  typedef charT char_type;

  typedef typename traits::int_type int_type;

  typedef typename traits::pos_type pos_type;

  typedef typename traits::off_type off_type;

  typedef traits traits_type;

  // Status

  operator void*(  );

  const bool operator!(  );

  const iostate rdstate(  ) const;

  void clear(iostate state = goodbit);

  void clear(io_state state);

  void setstate(iostate state);

  void setstate(io_state state);

  bool good(  ) const;

  bool eof(  ) const;

  bool fail(  ) const;

  bool bad(  ) const;

  iostate exceptions(  ) const;

  void exceptions(iostate except);

  void exceptions(io_state except);

  explicit basic_ios(basic_streambuf<charT,traits>* sb);

  virtual ~basic_ios(  );

  basic_ostream<charT,traits>* tie(  ) const;

  basic_ostream<charT,traits>* tie(basic_ostream<charT,traits>* tiestr);

  basic_streambuf<charT,traits>* rdbuf(  ) const;

  basic_streambuf<charT,traits>* rdbuf(basic_streambuf<charT,traits>* sb);

  basic_ios& copyfmt(const basic_ios& rhs);

  char_type fill(  ) const;

  char_type fill(char_type ch);

  locale imbue(const locale& loc);

  char narrow(char_type c, char deflt) const;

  char_type widen(char c) const;

protected:

  basic_ios(  );

  void init(basic_streambuf<charT,traits>* buf);

private:

  basic_ios(const basic_ios& );           // Not defined

  basic_ios& operator=(const basic_ios&); // Not defined

};

The basic_ios class template is the root of all I/O stream class templates. It provides a common functionality for all derived stream classes; in particular, it manages a stream buffer. In the following descriptions, the name buf refers to a private data member that points to the stream buffer. An implementation can use any name.

The following are the member functions of basic_ios:

basic_ios( )

The default constructor leaves the data members uninitialized. In a derived class, the default constructor must call init to initialize the members.

basic_ios(const basic_ios&)

The copy constructor is declared private and is not defined, which prevents the copying of any I/O stream objects.

explicit basic_ios(basic_streambuf<charT,traits>* sb)

Calls init(sb) to initialize the members.

operator void*( )

If fail( ) returns true, the void* operator returns a null pointer; otherwise, it returns a non-null pointer to indicate success. operator void* is most often used as an implicit conversion in a conditional (e.g., while (cin) cin >> data[i++]).

const bool operator!( )

Returns fail( ). operator ! is most often used in a conditional (e.g., if (!cout) cerr << "output error\n").

basic_ios& operator=(const basic_ios&)

The assignment operator, like the copy constructor, is private, so it cannot be used and is not defined. Assigning or copying an I/O stream would corrupt the stream buffer.

bool bad( ) const

Returns true if badbit is set in rdstate( ), or false otherwise.

void clear(iostate state = goodbit)
void clear(io_state state)

Sets the I/O state to state. If rdbuf( ) is a null pointer, badbit is also set (to state | ios_base::badbit). After setting the state, if any state bit is an exception bit ((rdstate( ) & exceptions( )) != 0), basic_ios::failure is thrown.

The second form is deprecated. See ios_base::iostate later in this section for details.

basic_ios& copyfmt(const basic_ios& rhs)

Copies formatting information from rhs. In particular, the format flags, fill character, locale, and the contents of the iword( ) and pword( ) arrays are copied. The I/O state and stream buffer are not copied. Before copying any callback functions, each one is called with erase_event. The callbacks are then replaced with those copied from rhs, and each one is called with copyfmt_event. (See ios_base for information about callbacks.) The exceptions( ) mask is copied last. The return value is *this.

bool eof( ) const

Returns true if eofbit is set in rdstate( ), or false otherwise.

iostate exceptions( ) const
void exceptions(iostate except)
void exceptions(io_state except)

Returns or sets the exception mask. (See the clear function for how and when an exception is thrown.) The third form is deprecated. See ios_base::iostate later in this section for details.

bool fail( ) const

Returns true if badbit is set or if failbit is set in rdstate( ), or false if neither bit is set.

char_type fill( ) const
char_type fill(char_type ch)

Returns or changes the fill character (also called the pad character). When setting the fill character, the old fill character is returned.

bool good( ) const

Returns true if the I/O state is cleanthat is, it returns rdstate( ) == 0.

locale imbue(const locale& loc)

Calls ios_base::imbue(loc) and rdbuf( )->pubimbue(loc) (if rdbuf( ) is not null). The return value is the previous value of ios_base::imbue( ).

void init(basic_streambuf<charT,traits>* buf)

Initializes the basic_ios object. Table 13-12 lists the observable effects of initialization. Also, the arrays for iword( ) and pword( ) are initially null pointers.

Table 13-12. Effects of calling basic_ios::init

Member function

Return value

exceptions( )

goodbit

fill( )

widen(' ')

flags( )

skipws | dec

getloc( )

Current global locale, that is, std::locale( )

precision( )

6

rdbuf( )

buf

rdstate( )

buf !=0 ? goodbit : badbit

tie( )

Null pointer

width( )

0

char narrow(char_type c, char deflt) const

Narrows the character c by returning the following:

std::use_facet<ctype<char_type> >(getloc(  )).narrow(c, deflt)
basic_streambuf<charT,traits>* rdbuf( ) const
basic_streambuf<charT,traits>*
rdbuf(basic_streambuf<charT,traits>* sb)

Returns or changes the stream buffer, buf. After changing the stream buffer, the rdbuf function calls clear( ). The function returns the previous value of rdbuf( ).

const iostate rdstate( ) const

Returns the current I/O state bitmask. See the bad, eof, fail, and good functions for convenient ways to test different bits in the state mask.

void setstate(iostate state)
void setstate(io_state state)

Sets the specified bits in the I/O state bitmaskthat is, it calls clear(rdstate( ) | state). The second form is deprecated. See ios_base::iostate later in this section for details.

basic_ostream<charT,traits>* tie( ) const
basic_ostream<charT,traits>* tie(basic_ostream<charT,traits>* tiestr)

Ties a stream (typically an input stream) to an output stream, tiestr. Any input operation on this stream is prefaced by flushing tiestr. Tying streams can be used to ensure that prompts appear at the proper time. With no arguments, the tie function returns the currently tied stream, or 0 if no stream is tied.

char_type widen(char c) const

Widens the character c by returning the following:

std::use_facet<ctype<char_type> >(getloc(  )).widen(c)

See Also

ios_base class, ctype in <locale>, basic_streambuf in <streambuf>

boolalpha function Manipulator for reading and writing bool as text

ios_base& boolalpha(ios_base& stream)

The boolalpha function is a manipulator that sets the boolalpha flag, which tells the stream to read or write a bool value as text, according to the stream's locale. Specifically, the function calls stream.setf(ios_base::boolalpha) and returns stream.

See Also

ios_base::fmtflags type, noboolalpha function, num_get in <locale>, num_put in <locale>

dec function Manipulator for decimal integers

ios_base& dec(ios_base& stream)

The dec function is a manipulator that sets the conversion radix to base 10. The function calls stream.setf(ios_base::dec, ios_base::basefield) and returns stream.

See Also

hex function, ios_base::fmtflags type, noshowbase function, oct function, showbase function, num_get in <locale>, num_put in <locale>

fixed function Manipulator for fixed-point output

ios_base& fixed(ios_base& stream)

The fixed function is a manipulator that sets the floating-point output style to fixed-point. The function calls stream.setf(ios_base::fixed, ios_base::floatfield) and returns stream.

See Also

ios_base::fmtflags type, noshowpoint function, scientific function, showpoint function, num_get in <locale>, num_put in <locale>

fpos class template Represents a file position

template <typename stateT>

class fpos{

public:

  stateT state(  ) const;

  void state(stateT);

   

  // The following functionality is required, although not necessarily as member

  // functions.

  fpos(int i);

  fpos(streamoff offset);

  operator streamoff(  ) const;

  bool operator==(const fpos& rhs) const;

  bool operator!=(const fpos& rhs) const;

  fpos operator+(streamoff offset) const;

  fpos operator-(streamoff offset) const;

  fpos& operator+=(streamoff offset);

  fpos& operator-=(streamoff offset);

  streamoff operator-(const fpos& rhs) const;

};

The fpos class template represents a position in a stream. The stateT template parameter is a multibyte shift state, such as mbstate_t. Objects of type fpos can be compared for equality or inequality, they can be subtracted to yield a stream offset, or a stream offset can be added to an fpos position to produce a new fpos. Also, stream offsets can be converted to and from fpos values. Although the declaration in this section shows these functions as member functions, they might be global functions or be provided in some other fashion.

The Shift State Problem

The C++ standard requires a library implementation to implement fpos<> and the streamoff types so that you can convert an object whose type is any fpos<> instance into a streamoff object and back again, recovering the original value.

Most library implementations do not work this way.

Instead, streamoff is usually implemented as an integral type, such as int or long. The problem is that fpos<> must store a stream position and a shift state, and the stream position is usually implemented with the same type as streamoff. In other words, converting from fpos<> to streamoff discards the shift state. The library cannot convert streamoff back to the original fpos<> because the original shift state is gone.

Note that char_traits has the same problem when specialized for char and wchar_t because its pos_type is defined to be streampos, which is defined in <iosfwd> to be fpos<mbstate_t>, and off_type is defined as streamoff.

The solution is not to convert a stream position to a stream offset. If you must do this, remember that you might be sacrificing the shift state. Save the shift state separately so you can restore it when converting a stream offset back to a stream position.

See Also

streamoff type, mbstate_t in <cwchar>

hex function Manipulator for hexadecimal integers

ios_base& hex(ios_base& stream)

The hex function is a manipulator that sets the conversion radix to base 16. The function calls stream.setf(ios_base::hex, ios_base::basefield) and returns stream.

See Also

dec function, ios_base::fmtflags type, noshowbase function, oct function, showbase function, num_get in <locale>, num_put in <locale>

internal function Manipulator to align output on an internal point

ios_base& internal(ios_base& stream)

The internal function is a manipulator that sets the stream's alignment to internal. The function calls stream.setf(ios_base::internal, ios_base::adjustfield) and returns stream. Internal padding works as follows:

  • If the formatted number begins with a sign, insert the padding after the sign.

  • If the formatted number begins with 0x or 0X, insert the padding after the x or X.

  • Otherwise, insert the padding before the number (like ios_base::right).

See Also

ios_base::fmtflags type, left function, right function

ios_base class Root class for I/O declarations

class ios_base{

public:

  class failure;

  typedef  . . .  fmtflags;

  typedef  . . .  iostate;

  typedef  . . .  io_state;

  typedef  . . .  openmode;

  typedef  . . .  open_mode;

  typedef  . . .  seekdir;

  typedef  . . .  seek_dir;

  typedef  . . .  streamoff;

  typedef  . . .  streampos;

  class Init;



  // Destructor

  virtual ~ios_base(  );

  // Formatting

  fmtflags flags(  ) const;

  fmtflags flags(fmtflags fmtfl);

  fmtflags setf(fmtflags fmtfl);

  fmtflags setf(fmtflags fmtfl, fmtflags mask);

  void unsetf(fmtflags mask);

  streamsize precision(  ) const;

  streamsize precision(streamsize prec);

  streamsize width(  ) const;

  streamsize width(streamsize wide);

  // Locales

  locale imbue(const locale& loc);

  locale getloc(  ) const;

  // Storage

  static int xalloc(  );

  long& iword(int index);

  void*& pword(int index);

  // Callbacks

  enum event { erase_event, imbue_event, copyfmt_event };

  typedef void (*event_callback)(event, ios_base&, int index);

  void register_callback(event_callback fn, int index);

  static bool sync_with_stdio(bool sync = true);

protected:

  ios_base(  );

private:

  ios_base(const ios_base&);

  ios_base& operator=(const ios_base&);

};

The ios_base class is the root class for all the I/O stream classes. It declares fundamental types that are used throughout the I/O library. It also has members to keep track of formatting for input and output, storing arbitrary information for derived classes, and registering functions to be called when something interesting happens to the stream object.

The io_state, open_mode, seek_dir, streamoff, and streampos types are deprecated and might not be included in a future revision of the C++ standard. The first three are integer types that are equivalent to iostate, openmode, and seekdir. (See their respective subsections later in this section for details.) The streamoff and streampos types have equivalent types at namespace scope. See streamoff later in this section and streampos in <iosfwd> for details.

The following are the member functions of ios_base:

ios_base( )

The default constructor is protected so you cannot accidentally declare an object of type ios_base. It does not initialize its members. That is left to the basic_ios::init function.

ios_base(const ios_base&)

The copy constructor is private and not defined so you cannot copy objects of type ios_base or its derived classes.

virtual ~ios_base( )

Calls every registered callback with the erase_event if the ios_base object has been properly initialized. See basic_ios::init.

ios_base& operator=(const ios_base&)

The assignment operator is private and not defined to prevent the assignment of ios_base objects or its derivatives.

fmtflags flags( ) const
fmtflags flags(fmtflags fmtfl)

Returns the current format flags or sets the flags. When setting the flags, the previous flags are returned.

locale getloc( ) const

Returns the stream's currently imbued locale.

locale imbue(const locale& loc)

Saves loc as the new locale and calls all registered callbacks with imbue_event. The new locale is stored before calling any callbacks, so if a callback function calls getloc, it gets the new locale.

long& iword(int index)

Returns a reference to a long integer that is stored in a private array, at index index. If iword has been called before with the same index, a reference to the array element is returned. Otherwise, the array is extended as needed so that index is a valid index, and the new entry is initialized to 0. A reference to the new element is returned.

The structure of the internal array is implementation-defined, and it might be a sparse array. The internal array grows as needed, and all prior values stored in the array are preserved, although the references might become invalid in any of the following situations:

  • After a call to iword with a different index

  • After calling basic_ios::copyfmt for this object

  • When the object is destroyed

If iword fails (perhaps because the internal array cannot grow), it returns a reference to a valid long& with a value that is initially 0. If the member function is called for an object whose class derives from basic_ios<>, badbit is set (which might throw ios_base::failure).

See the xalloc member function to learn how to obtain a suitable index.

streamsize precision( ) const
streamsize precision(streamsize prec)

Returns or sets the precision (places after the decimal point) used to format floating-point numbers for output. When setting a new precision, the previous precision is returned.

void*& pword(int index)

Returns a reference to a void* that is stored in a private array, at index index. If pword has been called before with the same index, a reference to the array element is returned. Otherwise, the array is extended as needed so that index is a valid index, and the new entry is initialized to a null pointer. A reference to the new element is returned.

The structure of the internal array is implementation-defined, and it might be a sparse array. The internal array grows as needed, and all prior values stored in the array are preserved, although the references might become invalid in any of the following situations:

  • After a call to pword with a different index

  • After calling basic_ios::copyfmt for this object

  • When the object is destroyed

If pword fails (perhaps because the internal array cannot grow), it returns a reference to a valid void*& with a value that is initially 0. If the object derives from basic_ios<>, badbit is set (which might throw ios_base::failure).

See the xalloc member function to learn how to obtain a suitable index.

void register_callback(event_callback fn, int index)

Registers a function fn to be called when one of three events occurs for the ios_base object:

  • The object is destroyed (erase_event)

  • copyfmt is called (erase_event followed by copyfmt_event)

  • imbue is called (imbue_event)

Each callback function is registered with an integer index. The index is passed to the callback function. Functions are called in the opposite order of registration. The callback function must not throw exceptions.

For example, suppose a program stores some debugging information with each stream. It allocates a struct and stores a pointer to the struct in the stream's pword array. When copyfmt is called, the debugging information should also be copied. Example 13-14 shows how to use callbacks to make sure the memory is managed properly.

Example 13-14. Copying information associated with streams
void manage_info(std::ios_base::event event,

                 std::ios_base& stream, int index)

{

  infostruct* ip;

   

  switch(event) {

  case std::ios_base::erase_event:

    ip = static_cast<infostruct*>(stream.pword(index));

    stream.pword(index) = 0;

    delete ip;

    break;

  case std::ios_base::copyfmt_event:

    stream.pword(index) = new infostruct;

    break;

  default:

    break; // imbue_event does not affect storage.

  }

}

   

void openread(std::ifstream& f, const char* name)

{

  f.open(name);

  int index = f.xalloc(  );

  f.pword(index) = new infostruct;

  f.register_callback(manage_info, index);

}
fmtflags setf(fmtflags addflags)

Sets the addflags bits of the formatting flags. It is equivalent to calling flags(flags( ) | addflags).

fmtflags setf(fmtflags newflags, fmtflags mask)

Clears the mask bits from the formatting flags and then sets the newflags & mask bits. It is equivalent to calling flags((flags( ) & ~mask) | (newflags & mask)). The two-argument version of setf is most often used with multiple-choice flags (e.g., setf(ios_base::dec, ios_base::basefield)).

static bool sync_with_stdio(bool sync = true)

Determines whether the standard C++ I/O objects are synchronized with the C I/O functions. Initially, they are synchronized.

figs/acorn.gif

If you call sync_with_stdio(false) after any I/O has been performed, the behavior is implementation-defined.

void unsetf(fmtflags mask)

Clears the mask bits from the formatting flags. It is equivalent to calling flags(flags( ) & ~mask).

streamsize width( ) const
streamsize width(streamsize wide)

Returns or sets the minimum field width. When setting the width, the previous width is returned.

static int xalloc( )

Returns a unique integer, suitable for use as an index to the iword or pword functions. You can think of ios_base as having a static integer data member, xalloc_index, and xalloc is implemented so it returns xalloc_index++.

See Also

basic_ios class template

ios_base::event type Callback event type

enum event { erase_event, imbue_event, copyfmt_event };

The ios_base::event type denotes an interesting event in the lifetime of an I/O stream object. See the register_callback function in the ios_base class, earlier in this section, to learn how to register a function that is called when one of these events occurs.

See Also

ios_base class, ios_base::event_callback type

ios_base::event_callback type Callback function type

typedef void (*event_callback)(event, ios_base&, int index);

The ios_base::event_callback type denotes a callback function. See the register_callback function in the ios_base class, earlier in this section, to learn how to register a callback function, which a stream object calls when an interesting event occurs.

See Also

ios_base class, ios_base::event type

ios_base::failure class Exception class for I/O failure

class ios_base::failure : public exception

{

public:

  explicit failure(const string& msg);

  virtual ~failure(  );

  virtual const char* what(  ) const throw(  );

};

The ios_base::failure class is the base class for I/O-related exceptions. Its use of the constructor's msg parameter and what( ) member function are consistent with the conventions of the exception class.

See Also

basic_ios::clear function, exception in <exception>

ios_base::fmtflags type Formatting flags

typedef  . . .  fmtflags;

static const fmtflags boolalpha;

static const fmtflags dec;

static const fmtflags fixed;

static const fmtflags hex;

static const fmtflags internal;

static const fmtflags left;

static const fmtflags oct;

static const fmtflags right;

static const fmtflags scientific;

static const fmtflags showbase;

static const fmtflags showpoint;

static const fmtflags showpos;

static const fmtflags skipws;

static const fmtflags unitbuf;

static const fmtflags uppercase;

static const fmtflags adjustfield;

static const fmtflags basefield;

static const fmtflags floatfield;

figs/acorn.gif

The fmtflags type is an integer, enum, or bitmask type (the exact type is implementation-defined) that represents formatting flags for input and output. In the ios_base class, several static constants are also defined, which can be implemented as enumerated literals or as explicit constants. Table 13-13 lists the flag literals.

Table 13-13. fmtflags literals

Literal name

Description

boolalpha

Reads and writes bool values as text, according to the locale

dec

Reads and writes decimal integers

fixed

Writes floating-point values in fixed notation

hex

Reads and writes hexadecimal integers

internal

Aligns output to internal point (e.g., after sign or 0x)

left

Left-aligns output

oct

Reads and writes octal integers

right

Right-aligns output

scientific

Writes floating-point values in scientific notation

showbase

Writes a prefix for an integer radix ( e.g., 0x for hexadecimal)

showpoint

Writes decimal point, even if not needed

showpos

Writes plus sign (+), even if not needed

skipws

Skips whitespace before input

unitbuf

Flushes output after each operation

uppercase

Uses uppercase in generated output (e.g., 0X prefix)

Some formatting items are Boolean: a flag is set or cleared. For example, the uppercase flag can be set to perform output in uppercase (that is, the 0X hexadecimal prefix or E in scientific notation), or the flag can be cleared for lowercase output. Other flags are set in fields. You can set a field to one of a number of values. Table 13-14 lists the field names, definitions, and the default behavior if the field value is 0. Each field name is used as a mask for the two-argument form of the ios_base::setf function.

Table 13-14. fmtflags constants

Constant name

Value

Default

adjustfield

left | internal | right

right

basefield

dec | hex | oct

Output: decInput: leading 0x or 0x is hex, 0 is oct, anything else is dec

floatfield

fixed | scientific

scientific if exponent is < -4 or precision, else fixed; strip trailing zeros and unneeded decimal point

See Also

ios_base class, ctype in <locale>, num_get in <locale>, num_put in <locale>

ios_base::Init class Initialization class

class ios_base::Init {

public:

  Init(  );

  ~Init(  );

};

The Init class is used to ensure that the construction of the standard I/O stream objects occurs. The first time an ios_base::Init object is constructed, it constructs and initializes cin, cout, cerr, clog, wcin, wcout, wcerr, and wclog. A static counter keeps track of the number of times ios_base::Init is constructed and destroyed. When the last instance is destroyed, flush( ) is called for cout, cerr, clog, wcout, wcerr, and wclog.

For example, suppose a program constructs a static object, and the constructor prints a warning to cerr if certain conditions hold. To ensure that cerr is properly initialized and ready to receive output, declare an ios_base::Init object before your static object, as shown in Example 13-15.

Example

Example 13-15. Ensuring proper initialization of standard I/O streams
class myclass {

public:

  myclass(  ) {

    if (! okay(  ))

      std::cerr << "Oops: not okay!\n";

  }

};

static std::ios_base::Init init;

static myclass myobject;

See Also

<iostream>

ios_base::iostate type I/O status

typedef  . . .  iostate

typedef  . . .  io_state

static const iostate badbitstatic const iostate eofbit

static const iostate failbit

static const iostate goodbit = iostate(0);

figs/acorn.gif

The ios_base::iostate type is an integer, enum, or bitset type (the exact type is implementation-defined) that represents the status of an I/O stream. The io_state type is an integral type that represents the same information. Some functions that take an iostate parameter have an overloaded version that accepts an io_state parameter and has the same functionality as its iostate counterpart. The io_state type and related functions are deprecated, so you should use the iostate versions.

Table 13-15 lists the iostate literals and their meanings. The basic_ios class template has several member functions for setting, testing, and clearing iostate bits.

Table 13-15. iostate literals

Literal

Description

badbit

Irrecoverable error, such as a null streambuf pointer or a write failure

eofbit

End-of-file when reading

failbit

Failure to read or write expected characters ( e.g., trying to read an integer from nonnumeric input)

goodbit

No problems; value is 0

See Also

basic_ios class template, <bitset>

ios_base::openmode type Open mode bits

typedef  . . .  openmode

typedef  . . .  open_mode

static const openmode app

static const openmode ate

static const openmode binary

static const openmode in

static const openmode out

static const openmode trunc