1 // File based streams -*- C++ -*-
3 // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
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, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
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
207 ? _M_buf_size - 1 : 1;
209 // Will be set to true if ::read() returns 0 indicating EOF.
210 bool __got_eof = false;
211 // Number of internal characters produced.
212 streamsize __ilen = 0;
213 codecvt_base::result __r = codecvt_base::ok;
214 if (__check_facet(_M_codecvt).always_noconv())
216 __ilen = _M_file.xsgetn(reinterpret_cast<char*>(this->eback()),
223 // Worst-case number of external bytes.
224 // XXX Not done encoding() == -1.
225 const int __enc = _M_codecvt->encoding();
226 streamsize __blen; // Minimum buffer size.
227 streamsize __rlen; // Number of chars to read.
229 __blen = __rlen = __buflen * __enc;
232 __blen = __buflen + _M_codecvt->max_length() - 1;
235 const streamsize __remainder = _M_ext_end - _M_ext_next;
236 __rlen = __rlen > __remainder ? __rlen - __remainder : 0;
238 // An imbue in 'read' mode implies first converting the external
239 // chars already present.
240 if (_M_reading && this->egptr() == this->eback() && __remainder)
243 // Allocate buffer if necessary and move unconverted
245 if (_M_ext_buf_size < __blen)
247 char* __buf = new char[__blen];
249 std::memcpy(__buf, _M_ext_next, __remainder);
251 delete [] _M_ext_buf;
253 _M_ext_buf_size = __blen;
255 else if (__remainder)
256 std::memmove(_M_ext_buf, _M_ext_next, __remainder);
258 _M_ext_next = _M_ext_buf;
259 _M_ext_end = _M_ext_buf + __remainder;
260 _M_state_last = _M_state_cur;
267 // This may fail if the return value of
268 // codecvt::max_length() is bogus.
269 if (_M_ext_end - _M_ext_buf + __rlen > _M_ext_buf_size)
271 __throw_ios_failure(__N("basic_filebuf::underflow "
272 "codecvt::max_length() "
275 streamsize __elen = _M_file.xsgetn(_M_ext_end, __rlen);
278 else if (__elen == -1)
280 _M_ext_end += __elen;
284 __r = _M_codecvt->in(_M_state_cur, _M_ext_next,
285 _M_ext_end, _M_ext_next, this->eback(),
286 this->eback() + __buflen, __iend);
287 if (__r == codecvt_base::noconv)
289 size_t __avail = _M_ext_end - _M_ext_buf;
290 __ilen = std::min(__avail, __buflen);
291 traits_type::copy(this->eback(),
292 reinterpret_cast<char_type*>(_M_ext_buf), __ilen);
293 _M_ext_next = _M_ext_buf + __ilen;
296 __ilen = __iend - this->eback();
298 // _M_codecvt->in may return error while __ilen > 0: this is
299 // ok, and actually occurs in case of mixed encodings (e.g.,
301 if (__r == codecvt_base::error)
306 while (__ilen == 0 && !__got_eof);
311 _M_set_buffer(__ilen);
313 __ret = traits_type::to_int_type(*this->gptr());
317 // If the actual end of file is reached, set 'uncommitted'
318 // mode, thus allowing an immediate write without an
322 // However, reaching it while looping on partial means that
323 // the file has got an incomplete character.
324 if (__r == codecvt_base::partial)
325 __throw_ios_failure(__N("basic_filebuf::underflow "
326 "incomplete character in file"));
328 else if (__r == codecvt_base::error)
329 __throw_ios_failure(__N("basic_filebuf::underflow "
330 "invalid byte sequence in file"));
332 __throw_ios_failure(__N("basic_filebuf::underflow "
333 "error reading the file"));
338 template<typename _CharT, typename _Traits>
339 typename basic_filebuf<_CharT, _Traits>::int_type
340 basic_filebuf<_CharT, _Traits>::
341 pbackfail(int_type __i)
343 int_type __ret = traits_type::eof();
344 const bool __testin = _M_mode & ios_base::in;
345 if (__testin && !_M_writing)
347 // Remember whether the pback buffer is active, otherwise below
348 // we may try to store in it a second char (libstdc++/9761).
349 const bool __testpb = _M_pback_init;
350 const bool __testeof = traits_type::eq_int_type(__i, __ret);
352 if (this->eback() < this->gptr())
355 __tmp = traits_type::to_int_type(*this->gptr());
357 else if (this->seekoff(-1, ios_base::cur) != pos_type(off_type(-1)))
359 __tmp = this->underflow();
360 if (traits_type::eq_int_type(__tmp, __ret))
365 // At the beginning of the buffer, need to make a
366 // putback position available. But the seek may fail
367 // (f.i., at the beginning of a file, see
368 // libstdc++/9439) and in that case we return
369 // traits_type::eof().
373 // Try to put back __i into input sequence in one of three ways.
374 // Order these tests done in is unspecified by the standard.
375 if (!__testeof && traits_type::eq_int_type(__i, __tmp))
378 __ret = traits_type::not_eof(__i);
383 *this->gptr() = traits_type::to_char_type(__i);
390 template<typename _CharT, typename _Traits>
391 typename basic_filebuf<_CharT, _Traits>::int_type
392 basic_filebuf<_CharT, _Traits>::
393 overflow(int_type __c)
395 int_type __ret = traits_type::eof();
396 const bool __testeof = traits_type::eq_int_type(__c, __ret);
397 const bool __testout = _M_mode & ios_base::out;
398 if (__testout && !_M_reading)
400 if (this->pbase() < this->pptr())
402 // If appropriate, append the overflow char.
405 *this->pptr() = traits_type::to_char_type(__c);
409 // Convert pending sequence to external representation,
411 if (_M_convert_to_external(this->pbase(),
412 this->pptr() - this->pbase()))
415 __ret = traits_type::not_eof(__c);
418 else if (_M_buf_size > 1)
420 // Overflow in 'uncommitted' mode: set _M_writing, set
421 // the buffer to the initial 'write' mode, and put __c
427 *this->pptr() = traits_type::to_char_type(__c);
430 __ret = traits_type::not_eof(__c);
435 char_type __conv = traits_type::to_char_type(__c);
436 if (__testeof || _M_convert_to_external(&__conv, 1))
439 __ret = traits_type::not_eof(__c);
446 template<typename _CharT, typename _Traits>
448 basic_filebuf<_CharT, _Traits>::
449 _M_convert_to_external(_CharT* __ibuf, streamsize __ilen)
451 // Sizes of external and pending output.
454 if (__check_facet(_M_codecvt).always_noconv())
456 __elen = _M_file.xsputn(reinterpret_cast<char*>(__ibuf), __ilen);
461 // Worst-case number of external bytes needed.
462 // XXX Not done encoding() == -1.
463 streamsize __blen = __ilen * _M_codecvt->max_length();
464 char* __buf = static_cast<char*>(__builtin_alloca(__blen));
467 const char_type* __iend;
468 codecvt_base::result __r;
469 __r = _M_codecvt->out(_M_state_cur, __ibuf, __ibuf + __ilen,
470 __iend, __buf, __buf + __blen, __bend);
472 if (__r == codecvt_base::ok || __r == codecvt_base::partial)
473 __blen = __bend - __buf;
474 else if (__r == codecvt_base::noconv)
476 // Same as the always_noconv case above.
477 __buf = reinterpret_cast<char*>(__ibuf);
481 __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
482 "conversion error"));
484 __elen = _M_file.xsputn(__buf, __blen);
487 // Try once more for partial conversions.
488 if (__r == codecvt_base::partial && __elen == __plen)
490 const char_type* __iresume = __iend;
491 streamsize __rlen = this->pptr() - __iend;
492 __r = _M_codecvt->out(_M_state_cur, __iresume,
493 __iresume + __rlen, __iend, __buf,
494 __buf + __blen, __bend);
495 if (__r != codecvt_base::error)
497 __rlen = __bend - __buf;
498 __elen = _M_file.xsputn(__buf, __rlen);
502 __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
503 "conversion error"));
506 return __elen == __plen;
509 template<typename _CharT, typename _Traits>
511 basic_filebuf<_CharT, _Traits>::
512 xsgetn(_CharT* __s, streamsize __n)
514 // Clear out pback buffer before going on to the real deal...
515 streamsize __ret = 0;
518 if (__n > 0 && this->gptr() == this->eback())
520 *__s++ = *this->gptr();
528 // Optimization in the always_noconv() case, to be generalized in the
529 // future: when __n > __buflen we read directly instead of using the
530 // buffer repeatedly.
531 const bool __testin = _M_mode & ios_base::in;
532 const streamsize __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1;
534 if (__n > __buflen && __check_facet(_M_codecvt).always_noconv()
535 && __testin && !_M_writing)
537 // First, copy the chars already present in the buffer.
538 const streamsize __avail = this->egptr() - this->gptr();
542 *__s = *this->gptr();
544 traits_type::copy(__s, this->gptr(), __avail);
546 this->gbump(__avail);
551 // Need to loop in case of short reads (relatively common
556 __len = _M_file.xsgetn(reinterpret_cast<char*>(__s),
559 __throw_ios_failure(__N("basic_filebuf::xsgetn "
560 "error reading the file"));
579 // If end of file is reached, set 'uncommitted'
580 // mode, thus allowing an immediate write without
581 // an intervening seek.
587 __ret += __streambuf_type::xsgetn(__s, __n);
592 template<typename _CharT, typename _Traits>
594 basic_filebuf<_CharT, _Traits>::
595 xsputn(const _CharT* __s, streamsize __n)
597 // Optimization in the always_noconv() case, to be generalized in the
598 // future: when __n is sufficiently large we write directly instead of
600 streamsize __ret = 0;
601 const bool __testout = _M_mode & ios_base::out;
602 if (__check_facet(_M_codecvt).always_noconv()
603 && __testout && !_M_reading)
605 // Measurement would reveal the best choice.
606 const streamsize __chunk = 1ul << 10;
607 streamsize __bufavail = this->epptr() - this->pptr();
609 // Don't mistake 'uncommitted' mode buffered with unbuffered.
610 if (!_M_writing && _M_buf_size > 1)
611 __bufavail = _M_buf_size - 1;
613 const streamsize __limit = std::min(__chunk, __bufavail);
616 const streamsize __buffill = this->pptr() - this->pbase();
617 const char* __buf = reinterpret_cast<const char*>(this->pbase());
618 __ret = _M_file.xsputn_2(__buf, __buffill,
619 reinterpret_cast<const char*>(__s),
621 if (__ret == __buffill + __n)
626 if (__ret > __buffill)
632 __ret = __streambuf_type::xsputn(__s, __n);
635 __ret = __streambuf_type::xsputn(__s, __n);
639 template<typename _CharT, typename _Traits>
640 typename basic_filebuf<_CharT, _Traits>::__streambuf_type*
641 basic_filebuf<_CharT, _Traits>::
642 setbuf(char_type* __s, streamsize __n)
644 if (!this->is_open())
645 if (__s == 0 && __n == 0)
647 else if (__s && __n > 0)
649 // This is implementation-defined behavior, and assumes that
650 // an external char_type array of length __n exists and has
651 // been pre-allocated. If this is not the case, things will
652 // quickly blow up. When __n > 1, __n - 1 positions will be
653 // used for the get area, __n - 1 for the put area and 1
654 // position to host the overflow char of a full put area.
655 // When __n == 1, 1 position will be used for the get area
656 // and 0 for the put area, as in the unbuffered case above.
664 // According to 27.8.1.4 p11 - 13, seekoff should ignore the last
665 // argument (of type openmode).
666 template<typename _CharT, typename _Traits>
667 typename basic_filebuf<_CharT, _Traits>::pos_type
668 basic_filebuf<_CharT, _Traits>::
669 seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode)
673 __width = _M_codecvt->encoding();
677 pos_type __ret = pos_type(off_type(-1));
678 const bool __testfail = __off != 0 && __width <= 0;
679 if (this->is_open() && !__testfail)
681 // Ditch any pback buffers to avoid confusion.
684 // Correct state at destination. Note that this is the correct
685 // state for the current position during output, because
686 // codecvt::unshift() returns the state to the initial state.
687 // This is also the correct state at the end of the file because
688 // an unshift sequence should have been written at the end.
689 __state_type __state = _M_state_beg;
690 off_type __computed_off = __off * __width;
691 if (_M_reading && __way == ios_base::cur)
693 if (_M_codecvt->always_noconv())
694 __computed_off += this->gptr() - this->egptr();
697 // Calculate offset from _M_ext_buf that corresponds
698 // to gptr(). Note: uses _M_state_last, which
699 // corresponds to eback().
700 const int __gptr_off =
701 _M_codecvt->length(_M_state_last, _M_ext_buf, _M_ext_next,
702 this->gptr() - this->eback());
703 __computed_off += _M_ext_buf + __gptr_off - _M_ext_end;
705 // _M_state_last is modified by codecvt::length() so
706 // it now corresponds to gptr().
707 __state = _M_state_last;
710 __ret = _M_seek(__computed_off, __way, __state);
715 // _GLIBCXX_RESOLVE_LIB_DEFECTS
716 // 171. Strange seekpos() semantics due to joint position
717 // According to the resolution of DR 171, seekpos should ignore the last
718 // argument (of type openmode).
719 template<typename _CharT, typename _Traits>
720 typename basic_filebuf<_CharT, _Traits>::pos_type
721 basic_filebuf<_CharT, _Traits>::
722 seekpos(pos_type __pos, ios_base::openmode)
724 pos_type __ret = pos_type(off_type(-1));
727 // Ditch any pback buffers to avoid confusion.
729 __ret = _M_seek(off_type(__pos), ios_base::beg, __pos.state());
734 template<typename _CharT, typename _Traits>
735 typename basic_filebuf<_CharT, _Traits>::pos_type
736 basic_filebuf<_CharT, _Traits>::
737 _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state)
739 pos_type __ret = pos_type(off_type(-1));
740 if (_M_terminate_output())
742 // Returns pos_type(off_type(-1)) in case of failure.
743 __ret = pos_type(_M_file.seekoff(__off, __way));
746 _M_ext_next = _M_ext_end = _M_ext_buf;
748 _M_state_cur = __state;
749 __ret.state(_M_state_cur);
754 template<typename _CharT, typename _Traits>
756 basic_filebuf<_CharT, _Traits>::
757 _M_terminate_output()
759 // Part one: update the output sequence.
760 bool __testvalid = true;
761 if (this->pbase() < this->pptr())
763 const int_type __tmp = this->overflow();
764 if (traits_type::eq_int_type(__tmp, traits_type::eof()))
768 // Part two: output unshift sequence.
769 if (_M_writing && !__check_facet(_M_codecvt).always_noconv()
772 // Note: this value is arbitrary, since there is no way to
773 // get the length of the unshift sequence from codecvt,
774 // without calling unshift.
775 const size_t __blen = 128;
777 codecvt_base::result __r;
778 streamsize __ilen = 0;
783 __r = _M_codecvt->unshift(_M_state_cur, __buf,
784 __buf + __blen, __next);
785 if (__r == codecvt_base::error)
787 else if (__r == codecvt_base::ok ||
788 __r == codecvt_base::partial)
790 __ilen = __next - __buf;
793 const streamsize __elen = _M_file.xsputn(__buf, __ilen);
794 if (__elen != __ilen)
799 while (__r == codecvt_base::partial && __ilen > 0 && __testvalid);
803 // This second call to overflow() is required by the standard,
804 // but it's not clear why it's needed, since the output buffer
805 // should be empty by this point (it should have been emptied
806 // in the first call to overflow()).
807 const int_type __tmp = this->overflow();
808 if (traits_type::eq_int_type(__tmp, traits_type::eof()))
815 template<typename _CharT, typename _Traits>
817 basic_filebuf<_CharT, _Traits>::
820 // Make sure that the internal buffer resyncs its idea of
821 // the file position with the external file.
823 if (this->pbase() < this->pptr())
825 const int_type __tmp = this->overflow();
826 if (traits_type::eq_int_type(__tmp, traits_type::eof()))
832 template<typename _CharT, typename _Traits>
834 basic_filebuf<_CharT, _Traits>::
835 imbue(const locale& __loc)
837 bool __testvalid = true;
839 const __codecvt_type* _M_codecvt_tmp = 0;
840 if (__builtin_expect(has_facet<__codecvt_type>(__loc), true))
841 _M_codecvt_tmp = &use_facet<__codecvt_type>(__loc);
845 // encoding() == -1 is ok only at the beginning.
846 if ((_M_reading || _M_writing)
847 && __check_facet(_M_codecvt).encoding() == -1)
853 if (__check_facet(_M_codecvt).always_noconv())
856 && !__check_facet(_M_codecvt_tmp).always_noconv())
857 __testvalid = this->seekoff(0, ios_base::cur, _M_mode)
858 != pos_type(off_type(-1));
862 // External position corresponding to gptr().
863 _M_ext_next = _M_ext_buf
864 + _M_codecvt->length(_M_state_last, _M_ext_buf, _M_ext_next,
865 this->gptr() - this->eback());
866 const streamsize __remainder = _M_ext_end - _M_ext_next;
868 std::memmove(_M_ext_buf, _M_ext_next, __remainder);
870 _M_ext_next = _M_ext_buf;
871 _M_ext_end = _M_ext_buf + __remainder;
873 _M_state_last = _M_state_cur = _M_state_beg;
876 else if (_M_writing && (__testvalid = _M_terminate_output()))
882 _M_codecvt = _M_codecvt_tmp;
887 // Inhibit implicit instantiations for required instantiations,
888 // which are defined via explicit instantiations elsewhere.
889 // NB: This syntax is a GNU extension.
890 #if _GLIBCXX_EXTERN_TEMPLATE
891 extern template class basic_filebuf<char>;
892 extern template class basic_ifstream<char>;
893 extern template class basic_ofstream<char>;
894 extern template class basic_fstream<char>;
896 #ifdef _GLIBCXX_USE_WCHAR_T
897 extern template class basic_filebuf<wchar_t>;
898 extern template class basic_ifstream<wchar_t>;
899 extern template class basic_ofstream<wchar_t>;
900 extern template class basic_fstream<wchar_t>;