libstdc++
fstream.tcc
Go to the documentation of this file.
00001 // File based streams -*- C++ -*-
00002 
00003 // Copyright (C) 1997-2013 Free Software Foundation, Inc.
00004 //
00005 // This file is part of the GNU ISO C++ Library.  This library is free
00006 // software; you can redistribute it and/or modify it under the
00007 // terms of the GNU General Public License as published by the
00008 // Free Software Foundation; either version 3, or (at your option)
00009 // any later version.
00010 
00011 // This library is distributed in the hope that it will be useful,
00012 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00013 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014 // GNU General Public License for more details.
00015 
00016 // Under Section 7 of GPL version 3, you are granted additional
00017 // permissions described in the GCC Runtime Library Exception, version
00018 // 3.1, as published by the Free Software Foundation.
00019 
00020 // You should have received a copy of the GNU General Public License and
00021 // a copy of the GCC Runtime Library Exception along with this program;
00022 // see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
00023 // <http://www.gnu.org/licenses/>.
00024 
00025 /** @file bits/fstream.tcc
00026  *  This is an internal header file, included by other library headers.
00027  *  Do not attempt to use it directly. @headername{fstream}
00028  */
00029 
00030 //
00031 // ISO C++ 14882: 27.8  File-based streams
00032 //
00033 
00034 #ifndef _FSTREAM_TCC
00035 #define _FSTREAM_TCC 1
00036 
00037 #pragma GCC system_header
00038 
00039 #include <bits/cxxabi_forced.h>
00040 
00041 namespace std _GLIBCXX_VISIBILITY(default)
00042 {
00043 _GLIBCXX_BEGIN_NAMESPACE_VERSION
00044 
00045   template<typename _CharT, typename _Traits>
00046     void
00047     basic_filebuf<_CharT, _Traits>::
00048     _M_allocate_internal_buffer()
00049     {
00050       // Allocate internal buffer only if one doesn't already exist
00051       // (either allocated or provided by the user via setbuf).
00052       if (!_M_buf_allocated && !_M_buf)
00053     {
00054       _M_buf = new char_type[_M_buf_size];
00055       _M_buf_allocated = true;
00056     }
00057     }
00058 
00059   template<typename _CharT, typename _Traits>
00060     void
00061     basic_filebuf<_CharT, _Traits>::
00062     _M_destroy_internal_buffer() throw()
00063     {
00064       if (_M_buf_allocated)
00065     {
00066       delete [] _M_buf;
00067       _M_buf = 0;
00068       _M_buf_allocated = false;
00069     }
00070       delete [] _M_ext_buf;
00071       _M_ext_buf = 0;
00072       _M_ext_buf_size = 0;
00073       _M_ext_next = 0;
00074       _M_ext_end = 0;
00075     }
00076 
00077   template<typename _CharT, typename _Traits>
00078     basic_filebuf<_CharT, _Traits>::
00079     basic_filebuf() : __streambuf_type(), _M_lock(), _M_file(&_M_lock),
00080     _M_mode(ios_base::openmode(0)), _M_state_beg(), _M_state_cur(),
00081     _M_state_last(), _M_buf(0), _M_buf_size(BUFSIZ),
00082     _M_buf_allocated(false), _M_reading(false), _M_writing(false), _M_pback(), 
00083     _M_pback_cur_save(0), _M_pback_end_save(0), _M_pback_init(false),
00084     _M_codecvt(0), _M_ext_buf(0), _M_ext_buf_size(0), _M_ext_next(0),
00085     _M_ext_end(0)
00086     {
00087       if (has_facet<__codecvt_type>(this->_M_buf_locale))
00088     _M_codecvt = &use_facet<__codecvt_type>(this->_M_buf_locale);
00089     }
00090 
00091   template<typename _CharT, typename _Traits>
00092     typename basic_filebuf<_CharT, _Traits>::__filebuf_type*
00093     basic_filebuf<_CharT, _Traits>::
00094     open(const char* __s, ios_base::openmode __mode)
00095     {
00096       __filebuf_type *__ret = 0;
00097       if (!this->is_open())
00098     {
00099       _M_file.open(__s, __mode);
00100       if (this->is_open())
00101         {
00102           _M_allocate_internal_buffer();
00103           _M_mode = __mode;
00104 
00105           // Setup initial buffer to 'uncommitted' mode.
00106           _M_reading = false;
00107           _M_writing = false;
00108           _M_set_buffer(-1);
00109 
00110           // Reset to initial state.
00111           _M_state_last = _M_state_cur = _M_state_beg;
00112 
00113           // 27.8.1.3,4
00114           if ((__mode & ios_base::ate)
00115           && this->seekoff(0, ios_base::end, __mode)
00116           == pos_type(off_type(-1)))
00117         this->close();
00118           else
00119         __ret = this;
00120         }
00121     }
00122       return __ret;
00123     }
00124 
00125   template<typename _CharT, typename _Traits>
00126     typename basic_filebuf<_CharT, _Traits>::__filebuf_type*
00127     basic_filebuf<_CharT, _Traits>::
00128     close()
00129     {
00130       if (!this->is_open())
00131     return 0;
00132 
00133       bool __testfail = false;
00134       {
00135     // NB: Do this here so that re-opened filebufs will be cool...
00136     struct __close_sentry
00137     {
00138       basic_filebuf *__fb;
00139       __close_sentry (basic_filebuf *__fbi): __fb(__fbi) { }
00140       ~__close_sentry ()
00141       {
00142         __fb->_M_mode = ios_base::openmode(0);
00143         __fb->_M_pback_init = false;
00144         __fb->_M_destroy_internal_buffer();
00145         __fb->_M_reading = false;
00146         __fb->_M_writing = false;
00147         __fb->_M_set_buffer(-1);
00148         __fb->_M_state_last = __fb->_M_state_cur = __fb->_M_state_beg;
00149       }
00150     } __cs (this);
00151 
00152     __try
00153       {
00154         if (!_M_terminate_output())
00155           __testfail = true;
00156       }
00157     __catch(__cxxabiv1::__forced_unwind&)
00158       {
00159         _M_file.close();
00160         __throw_exception_again;
00161       }
00162     __catch(...)
00163       { __testfail = true; }
00164       }
00165 
00166       if (!_M_file.close())
00167     __testfail = true;
00168 
00169       if (__testfail)
00170     return 0;
00171       else
00172     return this;
00173     }
00174 
00175   template<typename _CharT, typename _Traits>
00176     streamsize
00177     basic_filebuf<_CharT, _Traits>::
00178     showmanyc()
00179     {
00180       streamsize __ret = -1;
00181       const bool __testin = _M_mode & ios_base::in;
00182       if (__testin && this->is_open())
00183     {
00184       // For a stateful encoding (-1) the pending sequence might be just
00185       // shift and unshift prefixes with no actual character.
00186       __ret = this->egptr() - this->gptr();
00187 
00188 #if _GLIBCXX_HAVE_DOS_BASED_FILESYSTEM
00189       // About this workaround, see libstdc++/20806.
00190       const bool __testbinary = _M_mode & ios_base::binary;
00191       if (__check_facet(_M_codecvt).encoding() >= 0
00192           && __testbinary)
00193 #else
00194       if (__check_facet(_M_codecvt).encoding() >= 0)
00195 #endif
00196         __ret += _M_file.showmanyc() / _M_codecvt->max_length();
00197     }
00198       return __ret;
00199     }
00200 
00201   template<typename _CharT, typename _Traits>
00202     typename basic_filebuf<_CharT, _Traits>::int_type
00203     basic_filebuf<_CharT, _Traits>::
00204     underflow()
00205     {
00206       int_type __ret = traits_type::eof();
00207       const bool __testin = _M_mode & ios_base::in;
00208       if (__testin)
00209     {
00210       if (_M_writing)
00211         {
00212           if (overflow() == traits_type::eof())
00213         return __ret;
00214           _M_set_buffer(-1);
00215           _M_writing = false;
00216         }
00217       // Check for pback madness, and if so switch back to the
00218       // normal buffers and jet outta here before expensive
00219       // fileops happen...
00220       _M_destroy_pback();
00221 
00222       if (this->gptr() < this->egptr())
00223         return traits_type::to_int_type(*this->gptr());
00224 
00225       // Get and convert input sequence.
00226       const size_t __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1;
00227 
00228       // Will be set to true if ::read() returns 0 indicating EOF.
00229       bool __got_eof = false;
00230       // Number of internal characters produced.
00231       streamsize __ilen = 0;
00232       codecvt_base::result __r = codecvt_base::ok;
00233       if (__check_facet(_M_codecvt).always_noconv())
00234         {
00235           __ilen = _M_file.xsgetn(reinterpret_cast<char*>(this->eback()),
00236                       __buflen);
00237           if (__ilen == 0)
00238         __got_eof = true;
00239         }
00240       else
00241         {
00242               // Worst-case number of external bytes.
00243           // XXX Not done encoding() == -1.
00244           const int __enc = _M_codecvt->encoding();
00245           streamsize __blen; // Minimum buffer size.
00246           streamsize __rlen; // Number of chars to read.
00247           if (__enc > 0)
00248         __blen = __rlen = __buflen * __enc;
00249           else
00250         {
00251           __blen = __buflen + _M_codecvt->max_length() - 1;
00252           __rlen = __buflen;
00253         }
00254           const streamsize __remainder = _M_ext_end - _M_ext_next;
00255           __rlen = __rlen > __remainder ? __rlen - __remainder : 0;
00256 
00257           // An imbue in 'read' mode implies first converting the external
00258           // chars already present.
00259           if (_M_reading && this->egptr() == this->eback() && __remainder)
00260         __rlen = 0;
00261 
00262           // Allocate buffer if necessary and move unconverted
00263           // bytes to front.
00264           if (_M_ext_buf_size < __blen)
00265         {
00266           char* __buf = new char[__blen];
00267           if (__remainder)
00268             __builtin_memcpy(__buf, _M_ext_next, __remainder);
00269 
00270           delete [] _M_ext_buf;
00271           _M_ext_buf = __buf;
00272           _M_ext_buf_size = __blen;
00273         }
00274           else if (__remainder)
00275         __builtin_memmove(_M_ext_buf, _M_ext_next, __remainder);
00276 
00277           _M_ext_next = _M_ext_buf;
00278           _M_ext_end = _M_ext_buf + __remainder;
00279           _M_state_last = _M_state_cur;
00280 
00281           do
00282         {
00283           if (__rlen > 0)
00284             {
00285               // Sanity check!
00286               // This may fail if the return value of
00287               // codecvt::max_length() is bogus.
00288               if (_M_ext_end - _M_ext_buf + __rlen > _M_ext_buf_size)
00289             {
00290               __throw_ios_failure(__N("basic_filebuf::underflow "
00291                           "codecvt::max_length() "
00292                           "is not valid"));
00293             }
00294               streamsize __elen = _M_file.xsgetn(_M_ext_end, __rlen);
00295               if (__elen == 0)
00296             __got_eof = true;
00297               else if (__elen == -1)
00298             break;
00299               _M_ext_end += __elen;
00300             }
00301 
00302           char_type* __iend = this->eback();
00303           if (_M_ext_next < _M_ext_end)
00304             __r = _M_codecvt->in(_M_state_cur, _M_ext_next,
00305                      _M_ext_end, _M_ext_next,
00306                      this->eback(),
00307                      this->eback() + __buflen, __iend);
00308           if (__r == codecvt_base::noconv)
00309             {
00310               size_t __avail = _M_ext_end - _M_ext_buf;
00311               __ilen = std::min(__avail, __buflen);
00312               traits_type::copy(this->eback(),
00313                     reinterpret_cast<char_type*>
00314                     (_M_ext_buf), __ilen);
00315               _M_ext_next = _M_ext_buf + __ilen;
00316             }
00317           else
00318             __ilen = __iend - this->eback();
00319 
00320           // _M_codecvt->in may return error while __ilen > 0: this is
00321           // ok, and actually occurs in case of mixed encodings (e.g.,
00322           // XML files).
00323           if (__r == codecvt_base::error)
00324             break;
00325 
00326           __rlen = 1;
00327         }
00328           while (__ilen == 0 && !__got_eof);
00329         }
00330 
00331       if (__ilen > 0)
00332         {
00333           _M_set_buffer(__ilen);
00334           _M_reading = true;
00335           __ret = traits_type::to_int_type(*this->gptr());
00336         }
00337       else if (__got_eof)
00338         {
00339           // If the actual end of file is reached, set 'uncommitted'
00340           // mode, thus allowing an immediate write without an
00341           // intervening seek.
00342           _M_set_buffer(-1);
00343           _M_reading = false;
00344           // However, reaching it while looping on partial means that
00345           // the file has got an incomplete character.
00346           if (__r == codecvt_base::partial)
00347         __throw_ios_failure(__N("basic_filebuf::underflow "
00348                     "incomplete character in file"));
00349         }
00350       else if (__r == codecvt_base::error)
00351         __throw_ios_failure(__N("basic_filebuf::underflow "
00352                 "invalid byte sequence in file"));
00353       else
00354         __throw_ios_failure(__N("basic_filebuf::underflow "
00355                 "error reading the file"));
00356     }
00357       return __ret;
00358     }
00359 
00360   template<typename _CharT, typename _Traits>
00361     typename basic_filebuf<_CharT, _Traits>::int_type
00362     basic_filebuf<_CharT, _Traits>::
00363     pbackfail(int_type __i)
00364     {
00365       int_type __ret = traits_type::eof();
00366       const bool __testin = _M_mode & ios_base::in;
00367       if (__testin)
00368     {
00369       if (_M_writing)
00370         {
00371           if (overflow() == traits_type::eof())
00372         return __ret;
00373           _M_set_buffer(-1);
00374           _M_writing = false;
00375         }
00376       // Remember whether the pback buffer is active, otherwise below
00377       // we may try to store in it a second char (libstdc++/9761).
00378       const bool __testpb = _M_pback_init;
00379       const bool __testeof = traits_type::eq_int_type(__i, __ret);
00380       int_type __tmp;
00381       if (this->eback() < this->gptr())
00382         {
00383           this->gbump(-1);
00384           __tmp = traits_type::to_int_type(*this->gptr());
00385         }
00386       else if (this->seekoff(-1, ios_base::cur) != pos_type(off_type(-1)))
00387         {
00388           __tmp = this->underflow();
00389           if (traits_type::eq_int_type(__tmp, __ret))
00390         return __ret;
00391         }
00392       else
00393         {
00394           // At the beginning of the buffer, need to make a
00395           // putback position available.  But the seek may fail
00396           // (f.i., at the beginning of a file, see
00397           // libstdc++/9439) and in that case we return
00398           // traits_type::eof().
00399           return __ret;
00400         }
00401 
00402       // Try to put back __i into input sequence in one of three ways.
00403       // Order these tests done in is unspecified by the standard.
00404       if (!__testeof && traits_type::eq_int_type(__i, __tmp))
00405         __ret = __i;
00406       else if (__testeof)
00407         __ret = traits_type::not_eof(__i);
00408       else if (!__testpb)
00409         {
00410           _M_create_pback();
00411           _M_reading = true;
00412           *this->gptr() = traits_type::to_char_type(__i);
00413           __ret = __i;
00414         }
00415     }
00416       return __ret;
00417     }
00418 
00419   template<typename _CharT, typename _Traits>
00420     typename basic_filebuf<_CharT, _Traits>::int_type
00421     basic_filebuf<_CharT, _Traits>::
00422     overflow(int_type __c)
00423     {
00424       int_type __ret = traits_type::eof();
00425       const bool __testeof = traits_type::eq_int_type(__c, __ret);
00426       const bool __testout = _M_mode & ios_base::out;
00427       if (__testout)
00428     {
00429           if (_M_reading)
00430             {
00431               _M_destroy_pback();
00432               const int __gptr_off = _M_get_ext_pos(_M_state_last);
00433               if (_M_seek(__gptr_off, ios_base::cur, _M_state_last)
00434                   == pos_type(off_type(-1)))
00435                 return __ret;
00436             }
00437       if (this->pbase() < this->pptr())
00438         {
00439           // If appropriate, append the overflow char.
00440           if (!__testeof)
00441         {
00442           *this->pptr() = traits_type::to_char_type(__c);
00443           this->pbump(1);
00444         }
00445 
00446           // Convert pending sequence to external representation,
00447           // and output.
00448           if (_M_convert_to_external(this->pbase(),
00449                      this->pptr() - this->pbase()))
00450         {
00451           _M_set_buffer(0);
00452           __ret = traits_type::not_eof(__c);
00453         }
00454         }
00455       else if (_M_buf_size > 1)
00456         {
00457           // Overflow in 'uncommitted' mode: set _M_writing, set
00458           // the buffer to the initial 'write' mode, and put __c
00459           // into the buffer.
00460           _M_set_buffer(0);
00461           _M_writing = true;
00462           if (!__testeof)
00463         {
00464           *this->pptr() = traits_type::to_char_type(__c);
00465           this->pbump(1);
00466         }
00467           __ret = traits_type::not_eof(__c);
00468         }
00469       else
00470         {
00471           // Unbuffered.
00472           char_type __conv = traits_type::to_char_type(__c);
00473           if (__testeof || _M_convert_to_external(&__conv, 1))
00474         {
00475           _M_writing = true;
00476           __ret = traits_type::not_eof(__c);
00477         }
00478         }
00479     }
00480       return __ret;
00481     }
00482 
00483   template<typename _CharT, typename _Traits>
00484     bool
00485     basic_filebuf<_CharT, _Traits>::
00486     _M_convert_to_external(_CharT* __ibuf, streamsize __ilen)
00487     {
00488       // Sizes of external and pending output.
00489       streamsize __elen;
00490       streamsize __plen;
00491       if (__check_facet(_M_codecvt).always_noconv())
00492     {
00493       __elen = _M_file.xsputn(reinterpret_cast<char*>(__ibuf), __ilen);
00494       __plen = __ilen;
00495     }
00496       else
00497     {
00498       // Worst-case number of external bytes needed.
00499       // XXX Not done encoding() == -1.
00500       streamsize __blen = __ilen * _M_codecvt->max_length();
00501       char* __buf = static_cast<char*>(__builtin_alloca(__blen));
00502 
00503       char* __bend;
00504       const char_type* __iend;
00505       codecvt_base::result __r;
00506       __r = _M_codecvt->out(_M_state_cur, __ibuf, __ibuf + __ilen,
00507                 __iend, __buf, __buf + __blen, __bend);
00508 
00509       if (__r == codecvt_base::ok || __r == codecvt_base::partial)
00510         __blen = __bend - __buf;
00511       else if (__r == codecvt_base::noconv)
00512         {
00513           // Same as the always_noconv case above.
00514           __buf = reinterpret_cast<char*>(__ibuf);
00515           __blen = __ilen;
00516         }
00517       else
00518         __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
00519                     "conversion error"));
00520   
00521       __elen = _M_file.xsputn(__buf, __blen);
00522       __plen = __blen;
00523 
00524       // Try once more for partial conversions.
00525       if (__r == codecvt_base::partial && __elen == __plen)
00526         {
00527           const char_type* __iresume = __iend;
00528           streamsize __rlen = this->pptr() - __iend;
00529           __r = _M_codecvt->out(_M_state_cur, __iresume,
00530                     __iresume + __rlen, __iend, __buf,
00531                     __buf + __blen, __bend);
00532           if (__r != codecvt_base::error)
00533         {
00534           __rlen = __bend - __buf;
00535           __elen = _M_file.xsputn(__buf, __rlen);
00536           __plen = __rlen;
00537         }
00538           else
00539         __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
00540                     "conversion error"));
00541         }
00542     }
00543       return __elen == __plen;
00544     }
00545 
00546   template<typename _CharT, typename _Traits>
00547     streamsize
00548     basic_filebuf<_CharT, _Traits>::
00549     xsgetn(_CharT* __s, streamsize __n)
00550     {
00551       // Clear out pback buffer before going on to the real deal...
00552       streamsize __ret = 0;
00553       if (_M_pback_init)
00554     {
00555       if (__n > 0 && this->gptr() == this->eback())
00556         {
00557           *__s++ = *this->gptr(); // emulate non-underflowing sbumpc
00558           this->gbump(1);
00559           __ret = 1;
00560           --__n;
00561         }
00562       _M_destroy_pback();
00563     }
00564       else if (_M_writing)
00565     {
00566       if (overflow() == traits_type::eof())
00567         return __ret;
00568       _M_set_buffer(-1);
00569       _M_writing = false;
00570     }
00571  
00572       // Optimization in the always_noconv() case, to be generalized in the
00573       // future: when __n > __buflen we read directly instead of using the
00574       // buffer repeatedly.
00575       const bool __testin = _M_mode & ios_base::in;
00576       const streamsize __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1;
00577  
00578       if (__n > __buflen && __check_facet(_M_codecvt).always_noconv()
00579        && __testin)
00580      {
00581        // First, copy the chars already present in the buffer.
00582        const streamsize __avail = this->egptr() - this->gptr();
00583        if (__avail != 0)
00584          {
00585            traits_type::copy(__s, this->gptr(), __avail);
00586            __s += __avail;
00587            this->setg(this->eback(), this->gptr() + __avail,
00588               this->egptr());
00589            __ret += __avail;
00590            __n -= __avail;
00591          }
00592  
00593        // Need to loop in case of short reads (relatively common
00594        // with pipes).
00595        streamsize __len;
00596        for (;;)
00597          {
00598            __len = _M_file.xsgetn(reinterpret_cast<char*>(__s),
00599                       __n);
00600            if (__len == -1)
00601          __throw_ios_failure(__N("basic_filebuf::xsgetn "
00602                      "error reading the file"));
00603            if (__len == 0)
00604          break;
00605  
00606            __n -= __len;
00607            __ret += __len;
00608            if (__n == 0)
00609          break;
00610  
00611            __s += __len;
00612          }
00613  
00614        if (__n == 0)
00615          {
00616            _M_set_buffer(0);
00617            _M_reading = true;
00618          }
00619        else if (__len == 0)
00620          {
00621            // If end of file is reached, set 'uncommitted'
00622            // mode, thus allowing an immediate write without
00623            // an intervening seek.
00624            _M_set_buffer(-1);
00625            _M_reading = false;
00626          }
00627      }
00628       else
00629      __ret += __streambuf_type::xsgetn(__s, __n);
00630  
00631       return __ret;
00632     }
00633 
00634   template<typename _CharT, typename _Traits>
00635     streamsize
00636     basic_filebuf<_CharT, _Traits>::
00637     xsputn(const _CharT* __s, streamsize __n)
00638     {
00639       streamsize __ret = 0;
00640       // Optimization in the always_noconv() case, to be generalized in the
00641       // future: when __n is sufficiently large we write directly instead of
00642       // using the buffer.
00643       const bool __testout = _M_mode & ios_base::out;
00644       if (__check_facet(_M_codecvt).always_noconv()
00645        && __testout && !_M_reading)
00646     {
00647       // Measurement would reveal the best choice.
00648       const streamsize __chunk = 1ul << 10;
00649       streamsize __bufavail = this->epptr() - this->pptr();
00650 
00651       // Don't mistake 'uncommitted' mode buffered with unbuffered.
00652       if (!_M_writing && _M_buf_size > 1)
00653         __bufavail = _M_buf_size - 1;
00654 
00655       const streamsize __limit = std::min(__chunk, __bufavail);
00656       if (__n >= __limit)
00657         {
00658           const streamsize __buffill = this->pptr() - this->pbase();
00659           const char* __buf = reinterpret_cast<const char*>(this->pbase());
00660           __ret = _M_file.xsputn_2(__buf, __buffill,
00661                        reinterpret_cast<const char*>(__s),
00662                        __n);
00663           if (__ret == __buffill + __n)
00664         {
00665           _M_set_buffer(0);
00666           _M_writing = true;
00667         }
00668           if (__ret > __buffill)
00669         __ret -= __buffill;
00670           else
00671         __ret = 0;
00672         }
00673       else
00674         __ret = __streambuf_type::xsputn(__s, __n);
00675     }
00676        else
00677      __ret = __streambuf_type::xsputn(__s, __n);
00678        return __ret;
00679     }
00680 
00681   template<typename _CharT, typename _Traits>
00682     typename basic_filebuf<_CharT, _Traits>::__streambuf_type*
00683     basic_filebuf<_CharT, _Traits>::
00684     setbuf(char_type* __s, streamsize __n)
00685     {
00686       if (!this->is_open())
00687     {
00688       if (__s == 0 && __n == 0)
00689         _M_buf_size = 1;
00690       else if (__s && __n > 0)
00691         {
00692           // This is implementation-defined behavior, and assumes that
00693           // an external char_type array of length __n exists and has
00694           // been pre-allocated. If this is not the case, things will
00695           // quickly blow up. When __n > 1, __n - 1 positions will be
00696           // used for the get area, __n - 1 for the put area and 1
00697           // position to host the overflow char of a full put area.
00698           // When __n == 1, 1 position will be used for the get area
00699           // and 0 for the put area, as in the unbuffered case above.
00700           _M_buf = __s;
00701           _M_buf_size = __n;
00702         }
00703     }
00704       return this;
00705     }
00706 
00707 
00708   // According to 27.8.1.4 p11 - 13, seekoff should ignore the last
00709   // argument (of type openmode).
00710   template<typename _CharT, typename _Traits>
00711     typename basic_filebuf<_CharT, _Traits>::pos_type
00712     basic_filebuf<_CharT, _Traits>::
00713     seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode)
00714     {
00715       int __width = 0;
00716       if (_M_codecvt)
00717     __width = _M_codecvt->encoding();
00718       if (__width < 0)
00719     __width = 0;
00720 
00721       pos_type __ret = pos_type(off_type(-1));
00722       const bool __testfail = __off != 0 && __width <= 0;
00723       if (this->is_open() && !__testfail)
00724     {
00725       // tellg and tellp queries do not affect any state, unless
00726       // ! always_noconv and the put sequence is not empty.
00727       // In that case, determining the position requires converting the
00728       // put sequence. That doesn't use ext_buf, so requires a flush.
00729       bool __no_movement = __way == ios_base::cur && __off == 0
00730         && (!_M_writing || _M_codecvt->always_noconv());
00731 
00732       // Ditch any pback buffers to avoid confusion.
00733       if (!__no_movement)
00734         _M_destroy_pback();
00735 
00736       // Correct state at destination. Note that this is the correct
00737       // state for the current position during output, because
00738       // codecvt::unshift() returns the state to the initial state.
00739       // This is also the correct state at the end of the file because
00740       // an unshift sequence should have been written at the end.
00741       __state_type __state = _M_state_beg;
00742       off_type __computed_off = __off * __width;
00743       if (_M_reading && __way == ios_base::cur)
00744         {
00745           __state = _M_state_last;
00746           __computed_off += _M_get_ext_pos(__state);
00747         }
00748       if (!__no_movement)
00749         __ret = _M_seek(__computed_off, __way, __state);
00750       else
00751         {
00752           if (_M_writing)
00753         __computed_off = this->pptr() - this->pbase();
00754           
00755           off_type __file_off = _M_file.seekoff(0, ios_base::cur);
00756           if (__file_off != off_type(-1))
00757         {
00758           __ret = __file_off + __computed_off;
00759           __ret.state(__state);
00760         }
00761         }
00762     }
00763       return __ret;
00764     }
00765 
00766   // _GLIBCXX_RESOLVE_LIB_DEFECTS
00767   // 171. Strange seekpos() semantics due to joint position
00768   // According to the resolution of DR 171, seekpos should ignore the last
00769   // argument (of type openmode).
00770   template<typename _CharT, typename _Traits>
00771     typename basic_filebuf<_CharT, _Traits>::pos_type
00772     basic_filebuf<_CharT, _Traits>::
00773     seekpos(pos_type __pos, ios_base::openmode)
00774     {
00775       pos_type __ret =  pos_type(off_type(-1));
00776       if (this->is_open())
00777     {
00778       // Ditch any pback buffers to avoid confusion.
00779       _M_destroy_pback();
00780       __ret = _M_seek(off_type(__pos), ios_base::beg, __pos.state());
00781     }
00782       return __ret;
00783     }
00784 
00785   template<typename _CharT, typename _Traits>
00786     typename basic_filebuf<_CharT, _Traits>::pos_type
00787     basic_filebuf<_CharT, _Traits>::
00788     _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state)
00789     {
00790       pos_type __ret = pos_type(off_type(-1));
00791       if (_M_terminate_output())
00792     {
00793       off_type __file_off = _M_file.seekoff(__off, __way);
00794       if (__file_off != off_type(-1))
00795         {
00796           _M_reading = false;
00797           _M_writing = false;
00798           _M_ext_next = _M_ext_end = _M_ext_buf;
00799           _M_set_buffer(-1);
00800           _M_state_cur = __state;
00801           __ret = __file_off;
00802           __ret.state(_M_state_cur);
00803         }
00804     }
00805       return __ret;
00806     }
00807 
00808   // Returns the distance from the end of the ext buffer to the point
00809   // corresponding to gptr(). This is a negative value. Updates __state
00810   // from eback() correspondence to gptr().
00811   template<typename _CharT, typename _Traits>
00812     int basic_filebuf<_CharT, _Traits>::
00813     _M_get_ext_pos(__state_type& __state)
00814     {
00815       if (_M_codecvt->always_noconv())
00816         return this->gptr() - this->egptr();
00817       else
00818         {
00819           // Calculate offset from _M_ext_buf that corresponds to
00820           // gptr(). Precondition: __state == _M_state_last, which
00821           // corresponds to eback().
00822           const int __gptr_off =
00823             _M_codecvt->length(__state, _M_ext_buf, _M_ext_next,
00824                                this->gptr() - this->eback());
00825           return _M_ext_buf + __gptr_off - _M_ext_end;
00826         }
00827     }
00828     
00829   template<typename _CharT, typename _Traits>
00830     bool
00831     basic_filebuf<_CharT, _Traits>::
00832     _M_terminate_output()
00833     {
00834       // Part one: update the output sequence.
00835       bool __testvalid = true;
00836       if (this->pbase() < this->pptr())
00837     {
00838       const int_type __tmp = this->overflow();
00839       if (traits_type::eq_int_type(__tmp, traits_type::eof()))
00840         __testvalid = false;
00841     }
00842 
00843       // Part two: output unshift sequence.
00844       if (_M_writing && !__check_facet(_M_codecvt).always_noconv()
00845       && __testvalid)
00846     {
00847       // Note: this value is arbitrary, since there is no way to
00848       // get the length of the unshift sequence from codecvt,
00849       // without calling unshift.
00850       const size_t __blen = 128;
00851       char __buf[__blen];
00852       codecvt_base::result __r;
00853       streamsize __ilen = 0;
00854 
00855       do
00856         {
00857           char* __next;
00858           __r = _M_codecvt->unshift(_M_state_cur, __buf,
00859                     __buf + __blen, __next);
00860           if (__r == codecvt_base::error)
00861         __testvalid = false;
00862           else if (__r == codecvt_base::ok ||
00863                __r == codecvt_base::partial)
00864         {
00865           __ilen = __next - __buf;
00866           if (__ilen > 0)
00867             {
00868               const streamsize __elen = _M_file.xsputn(__buf, __ilen);
00869               if (__elen != __ilen)
00870             __testvalid = false;
00871             }
00872         }
00873         }
00874       while (__r == codecvt_base::partial && __ilen > 0 && __testvalid);
00875 
00876       if (__testvalid)
00877         {
00878           // This second call to overflow() is required by the standard,
00879           // but it's not clear why it's needed, since the output buffer
00880           // should be empty by this point (it should have been emptied
00881           // in the first call to overflow()).
00882           const int_type __tmp = this->overflow();
00883           if (traits_type::eq_int_type(__tmp, traits_type::eof()))
00884         __testvalid = false;
00885         }
00886     }
00887       return __testvalid;
00888     }
00889 
00890   template<typename _CharT, typename _Traits>
00891     int
00892     basic_filebuf<_CharT, _Traits>::
00893     sync()
00894     {
00895       // Make sure that the internal buffer resyncs its idea of
00896       // the file position with the external file.
00897       int __ret = 0;
00898       if (this->pbase() < this->pptr())
00899     {
00900       const int_type __tmp = this->overflow();
00901       if (traits_type::eq_int_type(__tmp, traits_type::eof()))
00902         __ret = -1;
00903     }
00904       return __ret;
00905     }
00906 
00907   template<typename _CharT, typename _Traits>
00908     void
00909     basic_filebuf<_CharT, _Traits>::
00910     imbue(const locale& __loc)
00911     {
00912       bool __testvalid = true;
00913 
00914       const __codecvt_type* _M_codecvt_tmp = 0;
00915       if (__builtin_expect(has_facet<__codecvt_type>(__loc), true))
00916     _M_codecvt_tmp = &use_facet<__codecvt_type>(__loc);
00917 
00918       if (this->is_open())
00919     {
00920       // encoding() == -1 is ok only at the beginning.
00921       if ((_M_reading || _M_writing)
00922           && __check_facet(_M_codecvt).encoding() == -1)
00923         __testvalid = false;
00924       else
00925         {
00926           if (_M_reading)
00927         {
00928           if (__check_facet(_M_codecvt).always_noconv())
00929             {
00930               if (_M_codecvt_tmp
00931               && !__check_facet(_M_codecvt_tmp).always_noconv())
00932             __testvalid = this->seekoff(0, ios_base::cur, _M_mode)
00933                           != pos_type(off_type(-1));
00934             }
00935           else
00936             {
00937               // External position corresponding to gptr().
00938               _M_ext_next = _M_ext_buf
00939             + _M_codecvt->length(_M_state_last, _M_ext_buf,
00940                          _M_ext_next,
00941                          this->gptr() - this->eback());
00942               const streamsize __remainder = _M_ext_end - _M_ext_next;
00943               if (__remainder)
00944             __builtin_memmove(_M_ext_buf, _M_ext_next, __remainder);
00945 
00946               _M_ext_next = _M_ext_buf;
00947               _M_ext_end = _M_ext_buf + __remainder;
00948               _M_set_buffer(-1);
00949               _M_state_last = _M_state_cur = _M_state_beg;
00950             }
00951         }
00952           else if (_M_writing && (__testvalid = _M_terminate_output()))
00953         _M_set_buffer(-1);
00954         }
00955     }
00956 
00957       if (__testvalid)
00958     _M_codecvt = _M_codecvt_tmp;
00959       else
00960     _M_codecvt = 0;
00961     }
00962 
00963   // Inhibit implicit instantiations for required instantiations,
00964   // which are defined via explicit instantiations elsewhere.
00965 #if _GLIBCXX_EXTERN_TEMPLATE
00966   extern template class basic_filebuf<char>;
00967   extern template class basic_ifstream<char>;
00968   extern template class basic_ofstream<char>;
00969   extern template class basic_fstream<char>;
00970 
00971 #ifdef _GLIBCXX_USE_WCHAR_T
00972   extern template class basic_filebuf<wchar_t>;
00973   extern template class basic_ifstream<wchar_t>;
00974   extern template class basic_ofstream<wchar_t>;
00975   extern template class basic_fstream<wchar_t>;
00976 #endif
00977 #endif
00978 
00979 _GLIBCXX_END_NAMESPACE_VERSION
00980 } // namespace std
00981 
00982 #endif