1 // File based streams -*- C++ -*-
3 // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
4 // Free Software Foundation, Inc.
6 // This file is part of the GNU ISO C++ Library. This library is free
7 // software; you can redistribute it and/or modify it under the
8 // terms of the GNU General Public License as published by the
9 // Free Software Foundation; either version 2, or (at your option)
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
17 // You should have received a copy of the GNU General Public License along
18 // with this library; see the file COPYING. If not, write to the Free
19 // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
22 // As a special exception, you may use this file as part of a free software
23 // library without restriction. Specifically, if other files instantiate
24 // templates or use macros or inline functions from this file, or you compile
25 // this file and link it with other files to produce an executable, this
26 // file does not by itself cause the resulting executable to be covered by
27 // the GNU General Public License. This exception does not however
28 // invalidate any other reasons why the executable file might be covered by
29 // the GNU General Public License.
32 * This is an internal header file, included by other library headers.
33 * You should not attempt to use it directly.
37 // ISO C++ 14882: 27.8 File-based streams
41 #define _FSTREAM_TCC 1
43 #pragma GCC system_header
47 template<typename _CharT, typename _Traits>
49 basic_filebuf<_CharT, _Traits>::
50 _M_allocate_internal_buffer()
52 // Allocate internal buffer only if one doesn't already exist
53 // (either allocated or provided by the user via setbuf).
54 if (!_M_buf_allocated && !_M_buf)
56 _M_buf = new char_type[_M_buf_size];
57 _M_buf_allocated = true;
61 template<typename _CharT, typename _Traits>
63 basic_filebuf<_CharT, _Traits>::
64 _M_destroy_internal_buffer() throw()
70 _M_buf_allocated = false;
79 template<typename _CharT, typename _Traits>
80 basic_filebuf<_CharT, _Traits>::
81 basic_filebuf() : __streambuf_type(), _M_lock(), _M_file(&_M_lock),
82 _M_mode(ios_base::openmode(0)), _M_state_beg(), _M_state_cur(),
83 _M_state_last(), _M_buf(NULL), _M_buf_size(BUFSIZ),
84 _M_buf_allocated(false), _M_reading(false), _M_writing(false), _M_pback(),
85 _M_pback_cur_save(0), _M_pback_end_save(0), _M_pback_init(false),
86 _M_codecvt(0), _M_ext_buf(0), _M_ext_buf_size(0), _M_ext_next(0),
89 if (has_facet<__codecvt_type>(this->_M_buf_locale))
90 _M_codecvt = &use_facet<__codecvt_type>(this->_M_buf_locale);
93 template<typename _CharT, typename _Traits>
94 typename basic_filebuf<_CharT, _Traits>::__filebuf_type*
95 basic_filebuf<_CharT, _Traits>::
96 open(const char* __s, ios_base::openmode __mode)
98 __filebuf_type *__ret = NULL;
101 _M_file.open(__s, __mode);
104 _M_allocate_internal_buffer();
107 // Setup initial buffer to 'uncommitted' mode.
112 // Reset to initial state.
113 _M_state_last = _M_state_cur = _M_state_beg;
116 if ((__mode & ios_base::ate)
117 && this->seekoff(0, ios_base::end, __mode)
118 == pos_type(off_type(-1)))
127 template<typename _CharT, typename _Traits>
128 typename basic_filebuf<_CharT, _Traits>::__filebuf_type*
129 basic_filebuf<_CharT, _Traits>::
132 __filebuf_type* __ret = NULL;
135 bool __testfail = false;
138 if (!_M_terminate_output())
142 { __testfail = true; }
144 // NB: Do this here so that re-opened filebufs will be cool...
145 _M_mode = ios_base::openmode(0);
146 _M_pback_init = false;
147 _M_destroy_internal_buffer();
151 _M_state_last = _M_state_cur = _M_state_beg;
153 if (!_M_file.close())
162 template<typename _CharT, typename _Traits>
164 basic_filebuf<_CharT, _Traits>::
167 streamsize __ret = -1;
168 const bool __testin = _M_mode & ios_base::in;
169 if (__testin && this->is_open())
171 // For a stateful encoding (-1) the pending sequence might be just
172 // shift and unshift prefixes with no actual character.
173 __ret = this->egptr() - this->gptr();
175 #if _GLIBCXX_HAVE_DOS_BASED_FILESYSTEM
176 // About this workaround, see libstdc++/20806.
177 const bool __testbinary = _M_mode & ios_base::binary;
178 if (__check_facet(_M_codecvt).encoding() >= 0
181 if (__check_facet(_M_codecvt).encoding() >= 0)
183 __ret += _M_file.showmanyc() / _M_codecvt->max_length();
188 template<typename _CharT, typename _Traits>
189 typename basic_filebuf<_CharT, _Traits>::int_type
190 basic_filebuf<_CharT, _Traits>::
193 int_type __ret = traits_type::eof();
194 const bool __testin = _M_mode & ios_base::in;
195 if (__testin && !_M_writing)
197 // Check for pback madness, and if so swich back to the
198 // normal buffers and jet outta here before expensive
202 if (this->gptr() < this->egptr())
203 return traits_type::to_int_type(*this->gptr());
205 // Get and convert input sequence.
206 const size_t __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1;
208 // Will be set to true if ::read() returns 0 indicating EOF.
209 bool __got_eof = false;
210 // Number of internal characters produced.
211 streamsize __ilen = 0;
212 codecvt_base::result __r = codecvt_base::ok;
213 if (__check_facet(_M_codecvt).always_noconv())
215 __ilen = _M_file.xsgetn(reinterpret_cast<char*>(this->eback()),
222 // Worst-case number of external bytes.
223 // XXX Not done encoding() == -1.
224 const int __enc = _M_codecvt->encoding();
225 streamsize __blen; // Minimum buffer size.
226 streamsize __rlen; // Number of chars to read.
228 __blen = __rlen = __buflen * __enc;
231 __blen = __buflen + _M_codecvt->max_length() - 1;
234 const streamsize __remainder = _M_ext_end - _M_ext_next;
235 __rlen = __rlen > __remainder ? __rlen - __remainder : 0;
237 // An imbue in 'read' mode implies first converting the external
238 // chars already present.
239 if (_M_reading && this->egptr() == this->eback() && __remainder)
242 // Allocate buffer if necessary and move unconverted
244 if (_M_ext_buf_size < __blen)
246 char* __buf = new char[__blen];
248 std::memcpy(__buf, _M_ext_next, __remainder);
250 delete [] _M_ext_buf;
252 _M_ext_buf_size = __blen;
254 else if (__remainder)
255 std::memmove(_M_ext_buf, _M_ext_next, __remainder);
257 _M_ext_next = _M_ext_buf;
258 _M_ext_end = _M_ext_buf + __remainder;
259 _M_state_last = _M_state_cur;
266 // This may fail if the return value of
267 // codecvt::max_length() is bogus.
268 if (_M_ext_end - _M_ext_buf + __rlen > _M_ext_buf_size)
270 __throw_ios_failure(__N("basic_filebuf::underflow "
271 "codecvt::max_length() "
274 streamsize __elen = _M_file.xsgetn(_M_ext_end, __rlen);
277 else if (__elen == -1)
279 _M_ext_end += __elen;
283 __r = _M_codecvt->in(_M_state_cur, _M_ext_next,
284 _M_ext_end, _M_ext_next, this->eback(),
285 this->eback() + __buflen, __iend);
286 if (__r == codecvt_base::noconv)
288 size_t __avail = _M_ext_end - _M_ext_buf;
289 __ilen = std::min(__avail, __buflen);
290 traits_type::copy(this->eback(),
291 reinterpret_cast<char_type*>(_M_ext_buf), __ilen);
292 _M_ext_next = _M_ext_buf + __ilen;
295 __ilen = __iend - this->eback();
297 // _M_codecvt->in may return error while __ilen > 0: this is
298 // ok, and actually occurs in case of mixed encodings (e.g.,
300 if (__r == codecvt_base::error)
305 while (__ilen == 0 && !__got_eof);
310 _M_set_buffer(__ilen);
312 __ret = traits_type::to_int_type(*this->gptr());
316 // If the actual end of file is reached, set 'uncommitted'
317 // mode, thus allowing an immediate write without an
321 // However, reaching it while looping on partial means that
322 // the file has got an incomplete character.
323 if (__r == codecvt_base::partial)
324 __throw_ios_failure(__N("basic_filebuf::underflow "
325 "incomplete character in file"));
327 else if (__r == codecvt_base::error)
328 __throw_ios_failure(__N("basic_filebuf::underflow "
329 "invalid byte sequence in file"));
331 __throw_ios_failure(__N("basic_filebuf::underflow "
332 "error reading the file"));
337 template<typename _CharT, typename _Traits>
338 typename basic_filebuf<_CharT, _Traits>::int_type
339 basic_filebuf<_CharT, _Traits>::
340 pbackfail(int_type __i)
342 int_type __ret = traits_type::eof();
343 const bool __testin = _M_mode & ios_base::in;
344 if (__testin && !_M_writing)
346 // Remember whether the pback buffer is active, otherwise below
347 // we may try to store in it a second char (libstdc++/9761).
348 const bool __testpb = _M_pback_init;
349 const bool __testeof = traits_type::eq_int_type(__i, __ret);
351 if (this->eback() < this->gptr())
354 __tmp = traits_type::to_int_type(*this->gptr());
356 else if (this->seekoff(-1, ios_base::cur) != pos_type(off_type(-1)))
358 __tmp = this->underflow();
359 if (traits_type::eq_int_type(__tmp, __ret))
364 // At the beginning of the buffer, need to make a
365 // putback position available. But the seek may fail
366 // (f.i., at the beginning of a file, see
367 // libstdc++/9439) and in that case we return
368 // traits_type::eof().
372 // Try to put back __i into input sequence in one of three ways.
373 // Order these tests done in is unspecified by the standard.
374 if (!__testeof && traits_type::eq_int_type(__i, __tmp))
377 __ret = traits_type::not_eof(__i);
382 *this->gptr() = traits_type::to_char_type(__i);
389 template<typename _CharT, typename _Traits>
390 typename basic_filebuf<_CharT, _Traits>::int_type
391 basic_filebuf<_CharT, _Traits>::
392 overflow(int_type __c)
394 int_type __ret = traits_type::eof();
395 const bool __testeof = traits_type::eq_int_type(__c, __ret);
396 const bool __testout = _M_mode & ios_base::out;
397 if (__testout && !_M_reading)
399 if (this->pbase() < this->pptr())
401 // If appropriate, append the overflow char.
404 *this->pptr() = traits_type::to_char_type(__c);
408 // Convert pending sequence to external representation,
410 if (_M_convert_to_external(this->pbase(),
411 this->pptr() - this->pbase()))
414 __ret = traits_type::not_eof(__c);
417 else if (_M_buf_size > 1)
419 // Overflow in 'uncommitted' mode: set _M_writing, set
420 // the buffer to the initial 'write' mode, and put __c
426 *this->pptr() = traits_type::to_char_type(__c);
429 __ret = traits_type::not_eof(__c);
434 char_type __conv = traits_type::to_char_type(__c);
435 if (__testeof || _M_convert_to_external(&__conv, 1))
438 __ret = traits_type::not_eof(__c);
445 template<typename _CharT, typename _Traits>
447 basic_filebuf<_CharT, _Traits>::
448 _M_convert_to_external(_CharT* __ibuf, streamsize __ilen)
450 // Sizes of external and pending output.
453 if (__check_facet(_M_codecvt).always_noconv())
455 __elen = _M_file.xsputn(reinterpret_cast<char*>(__ibuf), __ilen);
460 // Worst-case number of external bytes needed.
461 // XXX Not done encoding() == -1.
462 streamsize __blen = __ilen * _M_codecvt->max_length();
463 char* __buf = static_cast<char*>(__builtin_alloca(__blen));
466 const char_type* __iend;
467 codecvt_base::result __r;
468 __r = _M_codecvt->out(_M_state_cur, __ibuf, __ibuf + __ilen,
469 __iend, __buf, __buf + __blen, __bend);
471 if (__r == codecvt_base::ok || __r == codecvt_base::partial)
472 __blen = __bend - __buf;
473 else if (__r == codecvt_base::noconv)
475 // Same as the always_noconv case above.
476 __buf = reinterpret_cast<char*>(__ibuf);
480 __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
481 "conversion error"));
483 __elen = _M_file.xsputn(__buf, __blen);
486 // Try once more for partial conversions.
487 if (__r == codecvt_base::partial && __elen == __plen)
489 const char_type* __iresume = __iend;
490 streamsize __rlen = this->pptr() - __iend;
491 __r = _M_codecvt->out(_M_state_cur, __iresume,
492 __iresume + __rlen, __iend, __buf,
493 __buf + __blen, __bend);
494 if (__r != codecvt_base::error)
496 __rlen = __bend - __buf;
497 __elen = _M_file.xsputn(__buf, __rlen);
501 __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
502 "conversion error"));
505 return __elen == __plen;
508 template<typename _CharT, typename _Traits>
510 basic_filebuf<_CharT, _Traits>::
511 xsgetn(_CharT* __s, streamsize __n)
513 // Clear out pback buffer before going on to the real deal...
514 streamsize __ret = 0;
517 if (__n > 0 && this->gptr() == this->eback())
519 *__s++ = *this->gptr();
527 // Optimization in the always_noconv() case, to be generalized in the
528 // future: when __n > __buflen we read directly instead of using the
529 // buffer repeatedly.
530 const bool __testin = _M_mode & ios_base::in;
531 const streamsize __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1;
533 if (__n > __buflen && __check_facet(_M_codecvt).always_noconv()
534 && __testin && !_M_writing)
536 // First, copy the chars already present in the buffer.
537 const streamsize __avail = this->egptr() - this->gptr();
541 *__s = *this->gptr();
543 traits_type::copy(__s, this->gptr(), __avail);
545 this->gbump(__avail);
550 // Need to loop in case of short reads (relatively common
555 __len = _M_file.xsgetn(reinterpret_cast<char*>(__s),
558 __throw_ios_failure(__N("basic_filebuf::xsgetn "
559 "error reading the file"));
578 // If end of file is reached, set 'uncommitted'
579 // mode, thus allowing an immediate write without
580 // an intervening seek.
586 __ret += __streambuf_type::xsgetn(__s, __n);
591 template<typename _CharT, typename _Traits>
593 basic_filebuf<_CharT, _Traits>::
594 xsputn(const _CharT* __s, streamsize __n)
596 // Optimization in the always_noconv() case, to be generalized in the
597 // future: when __n is sufficiently large we write directly instead of
599 streamsize __ret = 0;
600 const bool __testout = _M_mode & ios_base::out;
601 if (__check_facet(_M_codecvt).always_noconv()
602 && __testout && !_M_reading)
604 // Measurement would reveal the best choice.
605 const streamsize __chunk = 1ul << 10;
606 streamsize __bufavail = this->epptr() - this->pptr();
608 // Don't mistake 'uncommitted' mode buffered with unbuffered.
609 if (!_M_writing && _M_buf_size > 1)
610 __bufavail = _M_buf_size - 1;
612 const streamsize __limit = std::min(__chunk, __bufavail);
615 const streamsize __buffill = this->pptr() - this->pbase();
616 const char* __buf = reinterpret_cast<const char*>(this->pbase());
617 __ret = _M_file.xsputn_2(__buf, __buffill,
618 reinterpret_cast<const char*>(__s),
620 if (__ret == __buffill + __n)
625 if (__ret > __buffill)
631 __ret = __streambuf_type::xsputn(__s, __n);
634 __ret = __streambuf_type::xsputn(__s, __n);
638 template<typename _CharT, typename _Traits>
639 typename basic_filebuf<_CharT, _Traits>::__streambuf_type*
640 basic_filebuf<_CharT, _Traits>::
641 setbuf(char_type* __s, streamsize __n)
643 if (!this->is_open())
644 if (__s == 0 && __n == 0)
646 else if (__s && __n > 0)
648 // This is implementation-defined behavior, and assumes that
649 // an external char_type array of length __n exists and has
650 // been pre-allocated. If this is not the case, things will
651 // quickly blow up. When __n > 1, __n - 1 positions will be
652 // used for the get area, __n - 1 for the put area and 1
653 // position to host the overflow char of a full put area.
654 // When __n == 1, 1 position will be used for the get area
655 // and 0 for the put area, as in the unbuffered case above.
663 // According to 27.8.1.4 p11 - 13, seekoff should ignore the last
664 // argument (of type openmode).
665 template<typename _CharT, typename _Traits>
666 typename basic_filebuf<_CharT, _Traits>::pos_type
667 basic_filebuf<_CharT, _Traits>::
668 seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode)
672 __width = _M_codecvt->encoding();
676 pos_type __ret = pos_type(off_type(-1));
677 const bool __testfail = __off != 0 && __width <= 0;
678 if (this->is_open() && !__testfail)
680 // Ditch any pback buffers to avoid confusion.
683 // Correct state at destination. Note that this is the correct
684 // state for the current position during output, because
685 // codecvt::unshift() returns the state to the initial state.
686 // This is also the correct state at the end of the file because
687 // an unshift sequence should have been written at the end.
688 __state_type __state = _M_state_beg;
689 off_type __computed_off = __off * __width;
690 if (_M_reading && __way == ios_base::cur)
692 if (_M_codecvt->always_noconv())
693 __computed_off += this->gptr() - this->egptr();
696 // Calculate offset from _M_ext_buf that corresponds
697 // to gptr(). Note: uses _M_state_last, which
698 // corresponds to eback().
699 const int __gptr_off =
700 _M_codecvt->length(_M_state_last, _M_ext_buf, _M_ext_next,
701 this->gptr() - this->eback());
702 __computed_off += _M_ext_buf + __gptr_off - _M_ext_end;
704 // _M_state_last is modified by codecvt::length() so
705 // it now corresponds to gptr().
706 __state = _M_state_last;
709 __ret = _M_seek(__computed_off, __way, __state);
714 // _GLIBCXX_RESOLVE_LIB_DEFECTS
715 // 171. Strange seekpos() semantics due to joint position
716 // According to the resolution of DR 171, seekpos should ignore the last
717 // argument (of type openmode).
718 template<typename _CharT, typename _Traits>
719 typename basic_filebuf<_CharT, _Traits>::pos_type
720 basic_filebuf<_CharT, _Traits>::
721 seekpos(pos_type __pos, ios_base::openmode)
723 pos_type __ret = pos_type(off_type(-1));
726 // Ditch any pback buffers to avoid confusion.
728 __ret = _M_seek(off_type(__pos), ios_base::beg, __pos.state());
733 template<typename _CharT, typename _Traits>
734 typename basic_filebuf<_CharT, _Traits>::pos_type
735 basic_filebuf<_CharT, _Traits>::
736 _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state)
738 pos_type __ret = pos_type(off_type(-1));
739 if (_M_terminate_output())
741 // Returns pos_type(off_type(-1)) in case of failure.
742 __ret = pos_type(_M_file.seekoff(__off, __way));
743 if (__ret != pos_type(off_type(-1)))
747 _M_ext_next = _M_ext_end = _M_ext_buf;
749 _M_state_cur = __state;
750 __ret.state(_M_state_cur);
756 template<typename _CharT, typename _Traits>
758 basic_filebuf<_CharT, _Traits>::
759 _M_terminate_output()
761 // Part one: update the output sequence.
762 bool __testvalid = true;
763 if (this->pbase() < this->pptr())
765 const int_type __tmp = this->overflow();
766 if (traits_type::eq_int_type(__tmp, traits_type::eof()))
770 // Part two: output unshift sequence.
771 if (_M_writing && !__check_facet(_M_codecvt).always_noconv()
774 // Note: this value is arbitrary, since there is no way to
775 // get the length of the unshift sequence from codecvt,
776 // without calling unshift.
777 const size_t __blen = 128;
779 codecvt_base::result __r;
780 streamsize __ilen = 0;
785 __r = _M_codecvt->unshift(_M_state_cur, __buf,
786 __buf + __blen, __next);
787 if (__r == codecvt_base::error)
789 else if (__r == codecvt_base::ok ||
790 __r == codecvt_base::partial)
792 __ilen = __next - __buf;
795 const streamsize __elen = _M_file.xsputn(__buf, __ilen);
796 if (__elen != __ilen)
801 while (__r == codecvt_base::partial && __ilen > 0 && __testvalid);
805 // This second call to overflow() is required by the standard,
806 // but it's not clear why it's needed, since the output buffer
807 // should be empty by this point (it should have been emptied
808 // in the first call to overflow()).
809 const int_type __tmp = this->overflow();
810 if (traits_type::eq_int_type(__tmp, traits_type::eof()))
817 template<typename _CharT, typename _Traits>
819 basic_filebuf<_CharT, _Traits>::
822 // Make sure that the internal buffer resyncs its idea of
823 // the file position with the external file.
825 if (this->pbase() < this->pptr())
827 const int_type __tmp = this->overflow();
828 if (traits_type::eq_int_type(__tmp, traits_type::eof()))
834 template<typename _CharT, typename _Traits>
836 basic_filebuf<_CharT, _Traits>::
837 imbue(const locale& __loc)
839 bool __testvalid = true;
841 const __codecvt_type* _M_codecvt_tmp = 0;
842 if (__builtin_expect(has_facet<__codecvt_type>(__loc), true))
843 _M_codecvt_tmp = &use_facet<__codecvt_type>(__loc);
847 // encoding() == -1 is ok only at the beginning.
848 if ((_M_reading || _M_writing)
849 && __check_facet(_M_codecvt).encoding() == -1)
855 if (__check_facet(_M_codecvt).always_noconv())
858 && !__check_facet(_M_codecvt_tmp).always_noconv())
859 __testvalid = this->seekoff(0, ios_base::cur, _M_mode)
860 != pos_type(off_type(-1));
864 // External position corresponding to gptr().
865 _M_ext_next = _M_ext_buf
866 + _M_codecvt->length(_M_state_last, _M_ext_buf, _M_ext_next,
867 this->gptr() - this->eback());
868 const streamsize __remainder = _M_ext_end - _M_ext_next;
870 std::memmove(_M_ext_buf, _M_ext_next, __remainder);
872 _M_ext_next = _M_ext_buf;
873 _M_ext_end = _M_ext_buf + __remainder;
875 _M_state_last = _M_state_cur = _M_state_beg;
878 else if (_M_writing && (__testvalid = _M_terminate_output()))
884 _M_codecvt = _M_codecvt_tmp;
889 // Inhibit implicit instantiations for required instantiations,
890 // which are defined via explicit instantiations elsewhere.
891 // NB: This syntax is a GNU extension.
892 #if _GLIBCXX_EXTERN_TEMPLATE
893 extern template class basic_filebuf<char>;
894 extern template class basic_ifstream<char>;
895 extern template class basic_ofstream<char>;
896 extern template class basic_fstream<char>;
898 #ifdef _GLIBCXX_USE_WCHAR_T
899 extern template class basic_filebuf<wchar_t>;
900 extern template class basic_ifstream<wchar_t>;
901 extern template class basic_ofstream<wchar_t>;
902 extern template class basic_fstream<wchar_t>;