libstdc++
fstream.tcc
Go to the documentation of this file.
1// File based streams -*- C++ -*-
2
3// Copyright (C) 1997-2024 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file bits/fstream.tcc
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{fstream}
28 */
29
30//
31// ISO C++ 14882: 27.8 File-based streams
32//
33
34#ifndef _FSTREAM_TCC
35#define _FSTREAM_TCC 1
36
37#pragma GCC system_header
38
39#include <bits/cxxabi_forced.h>
40#include <bits/move.h> // for swap
41#include <cerrno>
42
43namespace std _GLIBCXX_VISIBILITY(default)
44{
45_GLIBCXX_BEGIN_NAMESPACE_VERSION
46
47 template<typename _CharT, typename _Traits>
48 void
51 {
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)
55 {
56 _M_buf = new char_type[_M_buf_size];
57 _M_buf_allocated = true;
58 }
59 }
60
61 template<typename _CharT, typename _Traits>
62 void
65 {
66 if (_M_buf_allocated)
67 {
68 delete [] _M_buf;
69 _M_buf = 0;
70 _M_buf_allocated = false;
71 }
72 delete [] _M_ext_buf;
73 _M_ext_buf = 0;
74 _M_ext_buf_size = 0;
75 _M_ext_next = 0;
76 _M_ext_end = 0;
77 }
78
79 template<typename _CharT, typename _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(0), _M_buf_size(_GLIBCXX_BUFSIZ),
84 _M_buf_allocated(false), _M_reading(false), _M_writing(false), _M_pback(),
86 _M_codecvt(0), _M_ext_buf(0), _M_ext_buf_size(0), _M_ext_next(0),
87 _M_ext_end(0)
88 {
89 _M_codecvt = std::__try_use_facet<__codecvt_type>(this->_M_buf_locale);
90 }
91
92#if __cplusplus >= 201103L
93 template<typename _CharT, typename _Traits>
96 : __streambuf_type(__rhs),
97 _M_lock(), _M_file(std::move(__rhs._M_file), &_M_lock),
98 _M_mode(std::__exchange(__rhs._M_mode, ios_base::openmode(0))),
99 _M_state_beg(std::move(__rhs._M_state_beg)),
100 _M_state_cur(std::move(__rhs._M_state_cur)),
101 _M_state_last(std::move(__rhs._M_state_last)),
102 _M_buf(std::__exchange(__rhs._M_buf, nullptr)),
103 _M_buf_size(std::__exchange(__rhs._M_buf_size, 1)),
104 _M_buf_allocated(std::__exchange(__rhs._M_buf_allocated, false)),
105 _M_reading(std::__exchange(__rhs._M_reading, false)),
106 _M_writing(std::__exchange(__rhs._M_writing, false)),
107 _M_pback(__rhs._M_pback),
108 _M_pback_cur_save(std::__exchange(__rhs._M_pback_cur_save, nullptr)),
109 _M_pback_end_save(std::__exchange(__rhs._M_pback_end_save, nullptr)),
110 _M_pback_init(std::__exchange(__rhs._M_pback_init, false)),
111 _M_codecvt(__rhs._M_codecvt),
112 _M_ext_buf(std::__exchange(__rhs._M_ext_buf, nullptr)),
113 _M_ext_buf_size(std::__exchange(__rhs._M_ext_buf_size, 0)),
114 _M_ext_next(std::__exchange(__rhs._M_ext_next, nullptr)),
115 _M_ext_end(std::__exchange(__rhs._M_ext_end, nullptr))
116 {
117 __rhs._M_set_buffer(-1);
118 __rhs._M_state_last = __rhs._M_state_cur = __rhs._M_state_beg;
119 }
120
121 template<typename _CharT, typename _Traits>
122 basic_filebuf<_CharT, _Traits>&
123 basic_filebuf<_CharT, _Traits>::
124 operator=(basic_filebuf&& __rhs)
125 {
126 this->close();
127 __streambuf_type::operator=(__rhs);
128 _M_file.swap(__rhs._M_file);
129 _M_mode = std::__exchange(__rhs._M_mode, ios_base::openmode(0));
130 _M_state_beg = std::move(__rhs._M_state_beg);
131 _M_state_cur = std::move(__rhs._M_state_cur);
132 _M_state_last = std::move(__rhs._M_state_last);
133 _M_buf = std::__exchange(__rhs._M_buf, nullptr);
134 _M_buf_size = std::__exchange(__rhs._M_buf_size, 1);
135 _M_buf_allocated = std::__exchange(__rhs._M_buf_allocated, false);
136 _M_ext_buf = std::__exchange(__rhs._M_ext_buf, nullptr);
137 _M_ext_buf_size = std::__exchange(__rhs._M_ext_buf_size, 0);
138 _M_ext_next = std::__exchange(__rhs._M_ext_next, nullptr);
139 _M_ext_end = std::__exchange(__rhs._M_ext_end, nullptr);
140 _M_reading = std::__exchange(__rhs._M_reading, false);
141 _M_writing = std::__exchange(__rhs._M_writing, false);
142 _M_pback_cur_save = std::__exchange(__rhs._M_pback_cur_save, nullptr);
143 _M_pback_end_save = std::__exchange(__rhs._M_pback_end_save, nullptr);
144 _M_pback_init = std::__exchange(__rhs._M_pback_init, false);
145 __rhs._M_set_buffer(-1);
146 __rhs._M_state_last = __rhs._M_state_cur = __rhs._M_state_beg;
147 return *this;
148 }
149
150 template<typename _CharT, typename _Traits>
151 void
153 swap(basic_filebuf& __rhs)
154 {
155 __streambuf_type::swap(__rhs);
156 _M_file.swap(__rhs._M_file);
157 std::swap(_M_mode, __rhs._M_mode);
158 std::swap(_M_state_beg, __rhs._M_state_beg);
159 std::swap(_M_state_cur, __rhs._M_state_cur);
160 std::swap(_M_state_last, __rhs._M_state_last);
161 std::swap(_M_buf, __rhs._M_buf);
162 std::swap(_M_buf_size, __rhs._M_buf_size);
163 std::swap(_M_buf_allocated, __rhs._M_buf_allocated);
164 std::swap(_M_ext_buf, __rhs._M_ext_buf);
165 std::swap(_M_ext_buf_size, __rhs._M_ext_buf_size);
166 std::swap(_M_ext_next, __rhs._M_ext_next);
167 std::swap(_M_ext_end, __rhs._M_ext_end);
168 std::swap(_M_reading, __rhs._M_reading);
169 std::swap(_M_writing, __rhs._M_writing);
170 std::swap(_M_pback_cur_save, __rhs._M_pback_cur_save);
171 std::swap(_M_pback_end_save, __rhs._M_pback_end_save);
172 std::swap(_M_pback_init, __rhs._M_pback_init);
173 }
174#endif
175
176 template<typename _CharT, typename _Traits>
177 typename basic_filebuf<_CharT, _Traits>::__filebuf_type*
179 open(const char* __s, ios_base::openmode __mode)
180 {
181 __filebuf_type *__ret = 0;
182 if (!this->is_open())
183 {
184 _M_file.open(__s, __mode);
185 if (this->is_open())
186 {
187 _M_allocate_internal_buffer();
188 _M_mode = __mode;
189
190 // Setup initial buffer to 'uncommitted' mode.
191 _M_reading = false;
192 _M_writing = false;
193 _M_set_buffer(-1);
194
195 // Reset to initial state.
196 _M_state_last = _M_state_cur = _M_state_beg;
197
198 // 27.8.1.3,4
199 if ((__mode & ios_base::ate)
200 && this->seekoff(0, ios_base::end, __mode)
201 == pos_type(off_type(-1)))
202 this->close();
203 else
204 __ret = this;
205 }
206 }
207 return __ret;
208 }
209
210#if _GLIBCXX_HAVE__WFOPEN && _GLIBCXX_USE_WCHAR_T
211 template<typename _CharT, typename _Traits>
214 open(const wchar_t* __s, ios_base::openmode __mode)
215 {
216 __filebuf_type *__ret = 0;
217 if (!this->is_open())
218 {
219 _M_file.open(__s, __mode);
220 if (this->is_open())
221 {
222 _M_allocate_internal_buffer();
223 _M_mode = __mode;
224
225 // Setup initial buffer to 'uncommitted' mode.
226 _M_reading = false;
227 _M_writing = false;
228 _M_set_buffer(-1);
229
230 // Reset to initial state.
231 _M_state_last = _M_state_cur = _M_state_beg;
232
233 // 27.8.1.3,4
234 if ((__mode & ios_base::ate)
235 && this->seekoff(0, ios_base::end, __mode)
236 == pos_type(off_type(-1)))
237 this->close();
238 else
239 __ret = this;
240 }
241 }
242 return __ret;
243 }
244#endif // HAVE__WFOPEN && USE_WCHAR_T
246 template<typename _CharT, typename _Traits>
247 typename basic_filebuf<_CharT, _Traits>::__filebuf_type*
249 close()
250 {
251 if (!this->is_open())
252 return 0;
253
254 bool __testfail = false;
255 {
256 // NB: Do this here so that re-opened filebufs will be cool...
257 struct __close_sentry
258 {
259 basic_filebuf *__fb;
260 __close_sentry (basic_filebuf *__fbi): __fb(__fbi) { }
261 ~__close_sentry ()
262 {
263 __fb->_M_mode = ios_base::openmode(0);
264 __fb->_M_pback_init = false;
265 __fb->_M_destroy_internal_buffer();
266 __fb->_M_reading = false;
267 __fb->_M_writing = false;
268 __fb->_M_set_buffer(-1);
269 __fb->_M_state_last = __fb->_M_state_cur = __fb->_M_state_beg;
270 }
271 } __cs (this);
272
273 __try
274 {
275 if (!_M_terminate_output())
276 __testfail = true;
277 }
278 __catch(...)
279 {
280 _M_file.close();
281 __throw_exception_again;
282 }
283 }
284
285 if (!_M_file.close())
286 __testfail = true;
287
288 if (__testfail)
289 return 0;
290 else
291 return this;
292 }
293
294 template<typename _CharT, typename _Traits>
298 {
299 streamsize __ret = -1;
300 const bool __testin = _M_mode & ios_base::in;
301 if (__testin && this->is_open())
302 {
303 // For a stateful encoding (-1) the pending sequence might be just
304 // shift and unshift prefixes with no actual character.
305 __ret = this->egptr() - this->gptr();
306
307#if _GLIBCXX_HAVE_DOS_BASED_FILESYSTEM
308 // About this workaround, see libstdc++/20806.
309 const bool __testbinary = _M_mode & ios_base::binary;
310 if (__check_facet(_M_codecvt).encoding() >= 0
311 && __testbinary)
312#else
313 if (__check_facet(_M_codecvt).encoding() >= 0)
314#endif
315 __ret += _M_file.showmanyc() / _M_codecvt->max_length();
316 }
317 return __ret;
318 }
319
320 template<typename _CharT, typename _Traits>
321 typename basic_filebuf<_CharT, _Traits>::int_type
324 {
325 int_type __ret = traits_type::eof();
326 const bool __testin = _M_mode & ios_base::in;
327 if (__testin)
328 {
329 if (_M_writing)
330 {
331 if (overflow() == traits_type::eof())
332 return __ret;
333 _M_set_buffer(-1);
334 _M_writing = false;
335 }
336 // Check for pback madness, and if so switch back to the
337 // normal buffers and jet outta here before expensive
338 // fileops happen...
340
341 if (this->gptr() < this->egptr())
342 return traits_type::to_int_type(*this->gptr());
343
344 // Get and convert input sequence.
345 const size_t __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1;
346
347 // Will be set to true if ::read() returns 0 indicating EOF.
348 bool __got_eof = false;
349 // Number of internal characters produced.
350 streamsize __ilen = 0;
351 codecvt_base::result __r = codecvt_base::ok;
352 if (__check_facet(_M_codecvt).always_noconv())
353 {
354 __ilen = _M_file.xsgetn(reinterpret_cast<char*>(this->eback()),
355 __buflen);
356 if (__ilen == 0)
357 __got_eof = true;
358 }
359 else
360 {
361 // Worst-case number of external bytes.
362 // XXX Not done encoding() == -1.
363 const int __enc = _M_codecvt->encoding();
364 streamsize __blen; // Minimum buffer size.
365 streamsize __rlen; // Number of chars to read.
366 if (__enc > 0)
367 __blen = __rlen = __buflen * __enc;
368 else
369 {
370 __blen = __buflen + _M_codecvt->max_length() - 1;
371 __rlen = __buflen;
372 }
373 const streamsize __remainder = _M_ext_end - _M_ext_next;
374 __rlen = __rlen > __remainder ? __rlen - __remainder : 0;
375
376 // An imbue in 'read' mode implies first converting the external
377 // chars already present.
378 if (_M_reading && this->egptr() == this->eback() && __remainder)
379 __rlen = 0;
380
381 // Allocate buffer if necessary and move unconverted
382 // bytes to front.
383 if (_M_ext_buf_size < __blen)
384 {
385 char* __buf = new char[__blen];
386 if (__remainder)
387 __builtin_memcpy(__buf, _M_ext_next, __remainder);
388
389 delete [] _M_ext_buf;
390 _M_ext_buf = __buf;
391 _M_ext_buf_size = __blen;
392 }
393 else if (__remainder)
394 __builtin_memmove(_M_ext_buf, _M_ext_next, __remainder);
395
396 _M_ext_next = _M_ext_buf;
397 _M_ext_end = _M_ext_buf + __remainder;
398 _M_state_last = _M_state_cur;
399
400 do
401 {
402 if (__rlen > 0)
403 {
404 // Sanity check!
405 // This may fail if the return value of
406 // codecvt::max_length() is bogus.
407 if (_M_ext_end - _M_ext_buf + __rlen > _M_ext_buf_size)
408 {
409 __throw_ios_failure(__N("basic_filebuf::underflow "
410 "codecvt::max_length() "
411 "is not valid"));
413 streamsize __elen = _M_file.xsgetn(_M_ext_end, __rlen);
414 if (__elen == 0)
415 __got_eof = true;
416 else if (__elen == -1)
417 break;
418 _M_ext_end += __elen;
419 }
421 char_type* __iend = this->eback();
422 if (_M_ext_next < _M_ext_end)
423 __r = _M_codecvt->in(_M_state_cur, _M_ext_next,
424 _M_ext_end, _M_ext_next,
425 this->eback(),
426 this->eback() + __buflen, __iend);
427 if (__r == codecvt_base::noconv)
428 {
429 size_t __avail = _M_ext_end - _M_ext_buf;
430 __ilen = std::min(__avail, __buflen);
431 traits_type::copy(this->eback(),
432 reinterpret_cast<char_type*>
433 (_M_ext_buf), __ilen);
434 _M_ext_next = _M_ext_buf + __ilen;
435 }
436 else
437 __ilen = __iend - this->eback();
438
439 // _M_codecvt->in may return error while __ilen > 0: this is
440 // ok, and actually occurs in case of mixed encodings (e.g.,
441 // XML files).
442 if (__r == codecvt_base::error)
443 break;
444
445 __rlen = 1;
446 }
447 while (__ilen == 0 && !__got_eof);
448 }
449
450 if (__ilen > 0)
451 {
452 _M_set_buffer(__ilen);
454 __ret = traits_type::to_int_type(*this->gptr());
455 }
456 else if (__got_eof)
457 {
458 // If the actual end of file is reached, set 'uncommitted'
459 // mode, thus allowing an immediate write without an
460 // intervening seek.
461 _M_set_buffer(-1);
462 _M_reading = false;
463 // However, reaching it while looping on partial means that
464 // the file has got an incomplete character.
465 if (__r == codecvt_base::partial)
466 __throw_ios_failure(__N("basic_filebuf::underflow "
467 "incomplete character in file"));
468 }
469 else if (__r == codecvt_base::error)
470 __throw_ios_failure(__N("basic_filebuf::underflow "
471 "invalid byte sequence in file"));
472 else
473 __throw_ios_failure(__N("basic_filebuf::underflow "
474 "error reading the file"), errno);
475 }
476 return __ret;
478
479 template<typename _CharT, typename _Traits>
480 typename basic_filebuf<_CharT, _Traits>::int_type
482 pbackfail(int_type __i)
483 {
484 int_type __ret = traits_type::eof();
485 const bool __testin = _M_mode & ios_base::in;
486 if (__testin)
487 {
488 if (_M_writing)
489 {
490 if (overflow() == traits_type::eof())
491 return __ret;
492 _M_set_buffer(-1);
493 _M_writing = false;
494 }
495 // Remember whether the pback buffer is active, otherwise below
496 // we may try to store in it a second char (libstdc++/9761).
497 const bool __testpb = _M_pback_init;
498 const bool __testeof = traits_type::eq_int_type(__i, __ret);
499 int_type __tmp;
500 if (this->eback() < this->gptr())
501 {
502 this->gbump(-1);
503 __tmp = traits_type::to_int_type(*this->gptr());
504 }
505 else if (this->seekoff(-1, ios_base::cur) != pos_type(off_type(-1)))
506 {
507 __tmp = this->underflow();
508 if (traits_type::eq_int_type(__tmp, __ret))
509 return __ret;
510 }
511 else
512 {
513 // At the beginning of the buffer, need to make a
514 // putback position available. But the seek may fail
515 // (f.i., at the beginning of a file, see
516 // libstdc++/9439) and in that case we return
517 // traits_type::eof().
518 return __ret;
519 }
520
521 // Try to put back __i into input sequence in one of three ways.
522 // Order these tests done in is unspecified by the standard.
523 if (!__testeof && traits_type::eq_int_type(__i, __tmp))
524 __ret = __i;
525 else if (__testeof)
526 __ret = traits_type::not_eof(__i);
527 else if (!__testpb)
528 {
530 _M_reading = true;
531 *this->gptr() = traits_type::to_char_type(__i);
532 __ret = __i;
533 }
534 }
535 return __ret;
536 }
537
538 template<typename _CharT, typename _Traits>
539 typename basic_filebuf<_CharT, _Traits>::int_type
541 overflow(int_type __c)
542 {
543 int_type __ret = traits_type::eof();
544 const bool __testeof = traits_type::eq_int_type(__c, __ret);
545 const bool __testout = (_M_mode & ios_base::out
547 if (__testout)
548 {
549 if (_M_reading)
550 {
552 const int __gptr_off = _M_get_ext_pos(_M_state_last);
553 if (_M_seek(__gptr_off, ios_base::cur, _M_state_last)
554 == pos_type(off_type(-1)))
555 return __ret;
556 }
557 if (this->pbase() < this->pptr())
558 {
559 struct _Guard {
560 ~_Guard() { if (_M_p) _M_p->pbump(-1); }
561 basic_filebuf* _M_p;
562 };
563 _Guard __g = { };
564
565 // If appropriate, append the overflow char.
566 if (!__testeof)
567 {
568 *this->pptr() = traits_type::to_char_type(__c);
569 this->pbump(1);
570 __g._M_p = this;
571 }
572
573 // Convert pending sequence to external representation,
574 // and output.
575 if (_M_convert_to_external(this->pbase(),
576 this->pptr() - this->pbase()))
577 {
578 __g._M_p = 0;
579 _M_set_buffer(0);
580 __ret = traits_type::not_eof(__c);
581 }
582 }
583 else if (_M_buf_size > 1)
584 {
585 // Overflow in 'uncommitted' mode: set _M_writing, set
586 // the buffer to the initial 'write' mode, and put __c
587 // into the buffer.
588 _M_set_buffer(0);
589 _M_writing = true;
590 if (!__testeof)
591 {
592 *this->pptr() = traits_type::to_char_type(__c);
593 this->pbump(1);
594 }
595 __ret = traits_type::not_eof(__c);
596 }
597 else
598 {
599 // Unbuffered.
600 char_type __conv = traits_type::to_char_type(__c);
601 if (__testeof || _M_convert_to_external(&__conv, 1))
602 {
603 _M_writing = true;
604 __ret = traits_type::not_eof(__c);
605 }
606 }
607 }
608 return __ret;
609 }
610
611 template<typename _CharT, typename _Traits>
612 bool
614 _M_convert_to_external(_CharT* __ibuf, streamsize __ilen)
615 {
616 // Sizes of external and pending output.
617 streamsize __elen;
618 streamsize __plen;
619 if (__check_facet(_M_codecvt).always_noconv())
620 {
621 __elen = _M_file.xsputn(reinterpret_cast<char*>(__ibuf), __ilen);
622 __plen = __ilen;
623 }
624 else
625 {
626 // Worst-case number of external bytes needed.
627 // XXX Not done encoding() == -1.
628 streamsize __blen = __ilen * _M_codecvt->max_length();
629 char* __buf = static_cast<char*>(__builtin_alloca(__blen));
630
631 char* __bend;
632 const char_type* __iend;
633 codecvt_base::result __r;
634 __r = _M_codecvt->out(_M_state_cur, __ibuf, __ibuf + __ilen,
635 __iend, __buf, __buf + __blen, __bend);
636
637 if (__r == codecvt_base::ok || __r == codecvt_base::partial)
638 __blen = __bend - __buf;
639 else if (__r == codecvt_base::noconv)
640 {
641 // Same as the always_noconv case above.
642 __buf = reinterpret_cast<char*>(__ibuf);
643 __blen = __ilen;
644 }
645 else
646 __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
647 "conversion error"));
648
649 __elen = _M_file.xsputn(__buf, __blen);
650 __plen = __blen;
651
652 // Try once more for partial conversions.
653 if (__r == codecvt_base::partial && __elen == __plen)
654 {
655 const char_type* __iresume = __iend;
656 streamsize __rlen = this->pptr() - __iend;
657 __r = _M_codecvt->out(_M_state_cur, __iresume,
658 __iresume + __rlen, __iend, __buf,
659 __buf + __blen, __bend);
660 if (__r != codecvt_base::error)
661 {
662 __rlen = __bend - __buf;
663 __elen = _M_file.xsputn(__buf, __rlen);
664 __plen = __rlen;
665 }
666 else
667 __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
668 "conversion error"));
669 }
670 }
671 return __elen == __plen;
672 }
673
674 template<typename _CharT, typename _Traits>
677 xsgetn(_CharT* __s, streamsize __n)
678 {
679 // Clear out pback buffer before going on to the real deal...
680 streamsize __ret = 0;
681 if (_M_pback_init)
682 {
683 if (__n > 0 && this->gptr() == this->eback())
684 {
685 *__s++ = *this->gptr(); // emulate non-underflowing sbumpc
686 this->gbump(1);
687 __ret = 1;
688 --__n;
689 }
691 }
692 else if (_M_writing)
693 {
694 if (overflow() == traits_type::eof())
695 return __ret;
696 _M_set_buffer(-1);
697 _M_writing = false;
698 }
699
700 // Optimization in the always_noconv() case, to be generalized in the
701 // future: when __n > __buflen we read directly instead of using the
702 // buffer repeatedly.
703 const bool __testin = _M_mode & ios_base::in;
704 const streamsize __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1;
705
706 if (__n > __buflen && __check_facet(_M_codecvt).always_noconv()
707 && __testin)
708 {
709 // First, copy the chars already present in the buffer.
710 const streamsize __avail = this->egptr() - this->gptr();
711 if (__avail != 0)
712 {
713 traits_type::copy(__s, this->gptr(), __avail);
714 __s += __avail;
715 this->setg(this->eback(), this->gptr() + __avail, this->egptr());
716 __ret += __avail;
717 __n -= __avail;
718 }
719
720 // Need to loop in case of short reads (relatively common
721 // with pipes).
722 streamsize __len;
723 for (;;)
724 {
725 __len = _M_file.xsgetn(reinterpret_cast<char*>(__s), __n);
726 if (__len == -1)
727 __throw_ios_failure(__N("basic_filebuf::xsgetn "
728 "error reading the file"), errno);
729 if (__len == 0)
730 break;
731
732 __n -= __len;
733 __ret += __len;
734 if (__n == 0)
735 break;
736
737 __s += __len;
738 }
739
740 if (__n == 0)
741 {
742 // Set _M_reading. Buffer is already in initial 'read' mode.
743 _M_reading = true;
744 }
745 else if (__len == 0)
746 {
747 // If end of file is reached, set 'uncommitted'
748 // mode, thus allowing an immediate write without
749 // an intervening seek.
750 _M_set_buffer(-1);
751 _M_reading = false;
752 }
753 }
754 else
755 __ret += __streambuf_type::xsgetn(__s, __n);
756
757 return __ret;
758 }
759
760 template<typename _CharT, typename _Traits>
763 xsputn(const _CharT* __s, streamsize __n)
764 {
765 streamsize __ret = 0;
766 // Optimization in the always_noconv() case, to be generalized in the
767 // future: when __n is larger than the available capacity we write
768 // directly instead of using the buffer.
769 const bool __testout = (_M_mode & ios_base::out
771 if (__check_facet(_M_codecvt).always_noconv()
772 && __testout && !_M_reading)
773 {
774 streamsize __bufavail = this->epptr() - this->pptr();
775
776 // Don't mistake 'uncommitted' mode buffered with unbuffered.
777 if (!_M_writing && _M_buf_size > 1)
778 __bufavail = _M_buf_size - 1;
779
780 if (__n >= __bufavail)
781 {
782 const streamsize __buffill = this->pptr() - this->pbase();
783 const char* __buf = reinterpret_cast<const char*>(this->pbase());
784 __ret = _M_file.xsputn_2(__buf, __buffill,
785 reinterpret_cast<const char*>(__s),
786 __n);
787 if (__ret == __buffill + __n)
788 {
789 _M_set_buffer(0);
790 _M_writing = true;
791 }
792 if (__ret > __buffill)
793 __ret -= __buffill;
794 else
795 __ret = 0;
796 }
797 else
798 __ret = __streambuf_type::xsputn(__s, __n);
799 }
800 else
801 __ret = __streambuf_type::xsputn(__s, __n);
802 return __ret;
803 }
804
805 template<typename _CharT, typename _Traits>
806 typename basic_filebuf<_CharT, _Traits>::__streambuf_type*
808 setbuf(char_type* __s, streamsize __n)
809 {
810 if (!this->is_open())
811 {
812 if (__s == 0 && __n == 0)
813 _M_buf_size = 1;
814 else if (__s && __n > 0)
815 {
816 // This is implementation-defined behavior, and assumes that
817 // an external char_type array of length __n exists and has
818 // been pre-allocated. If this is not the case, things will
819 // quickly blow up. When __n > 1, __n - 1 positions will be
820 // used for the get area, __n - 1 for the put area and 1
821 // position to host the overflow char of a full put area.
822 // When __n == 1, 1 position will be used for the get area
823 // and 0 for the put area, as in the unbuffered case above.
824 _M_buf = __s;
825 _M_buf_size = __n;
826 }
827 }
828 return this;
829 }
830
831
832 // According to 27.8.1.4 p11 - 13, seekoff should ignore the last
833 // argument (of type openmode).
834 template<typename _CharT, typename _Traits>
835 typename basic_filebuf<_CharT, _Traits>::pos_type
837 seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode)
838 {
839 int __width = 0;
840 if (_M_codecvt)
841 __width = _M_codecvt->encoding();
842 if (__width < 0)
843 __width = 0;
844
845 pos_type __ret = pos_type(off_type(-1));
846 const bool __testfail = __off != 0 && __width <= 0;
847 if (this->is_open() && !__testfail)
848 {
849 // tellg and tellp queries do not affect any state, unless
850 // ! always_noconv and the put sequence is not empty.
851 // In that case, determining the position requires converting the
852 // put sequence. That doesn't use ext_buf, so requires a flush.
853 bool __no_movement = __way == ios_base::cur && __off == 0
854 && (!_M_writing || _M_codecvt->always_noconv());
855
856 // Ditch any pback buffers to avoid confusion.
857 if (!__no_movement)
859
860 // Correct state at destination. Note that this is the correct
861 // state for the current position during output, because
862 // codecvt::unshift() returns the state to the initial state.
863 // This is also the correct state at the end of the file because
864 // an unshift sequence should have been written at the end.
865 __state_type __state = _M_state_beg;
866 off_type __computed_off = __off * __width;
867 if (_M_reading && __way == ios_base::cur)
868 {
869 __state = _M_state_last;
870 __computed_off += _M_get_ext_pos(__state);
871 }
872 if (!__no_movement)
873 __ret = _M_seek(__computed_off, __way, __state);
874 else
875 {
876 if (_M_writing)
877 __computed_off = this->pptr() - this->pbase();
878
879 off_type __file_off = _M_file.seekoff(0, ios_base::cur);
880 if (__file_off != off_type(-1))
881 {
882 __ret = __file_off + __computed_off;
883 __ret.state(__state);
884 }
885 }
886 }
887 return __ret;
888 }
889
890 // _GLIBCXX_RESOLVE_LIB_DEFECTS
891 // 171. Strange seekpos() semantics due to joint position
892 // According to the resolution of DR 171, seekpos should ignore the last
893 // argument (of type openmode).
894 template<typename _CharT, typename _Traits>
895 typename basic_filebuf<_CharT, _Traits>::pos_type
897 seekpos(pos_type __pos, ios_base::openmode)
898 {
899 pos_type __ret = pos_type(off_type(-1));
900 if (this->is_open())
901 {
902 // Ditch any pback buffers to avoid confusion.
904 __ret = _M_seek(off_type(__pos), ios_base::beg, __pos.state());
905 }
906 return __ret;
907 }
908
909 template<typename _CharT, typename _Traits>
910 typename basic_filebuf<_CharT, _Traits>::pos_type
912 _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state)
913 {
914 pos_type __ret = pos_type(off_type(-1));
915 if (_M_terminate_output())
916 {
917 off_type __file_off = _M_file.seekoff(__off, __way);
918 if (__file_off != off_type(-1))
919 {
920 _M_reading = false;
921 _M_writing = false;
922 _M_ext_next = _M_ext_end = _M_ext_buf;
923 _M_set_buffer(-1);
924 _M_state_cur = __state;
925 __ret = __file_off;
926 __ret.state(_M_state_cur);
927 }
928 }
929 return __ret;
930 }
931
932 // Returns the distance from the end of the ext buffer to the point
933 // corresponding to gptr(). This is a negative value. Updates __state
934 // from eback() correspondence to gptr().
935 template<typename _CharT, typename _Traits>
937 _M_get_ext_pos(__state_type& __state)
938 {
939 if (_M_codecvt->always_noconv())
940 return this->gptr() - this->egptr();
941 else
942 {
943 // Calculate offset from _M_ext_buf that corresponds to
944 // gptr(). Precondition: __state == _M_state_last, which
945 // corresponds to eback().
946 const int __gptr_off =
947 _M_codecvt->length(__state, _M_ext_buf, _M_ext_next,
948 this->gptr() - this->eback());
949 return _M_ext_buf + __gptr_off - _M_ext_end;
950 }
951 }
952
953 template<typename _CharT, typename _Traits>
954 bool
957 {
958 // Part one: update the output sequence.
959 bool __testvalid = true;
960 if (this->pbase() < this->pptr())
961 {
962 const int_type __tmp = this->overflow();
963 if (traits_type::eq_int_type(__tmp, traits_type::eof()))
964 __testvalid = false;
965 }
966
967 // Part two: output unshift sequence.
968 if (_M_writing && !__check_facet(_M_codecvt).always_noconv()
969 && __testvalid)
970 {
971 // Note: this value is arbitrary, since there is no way to
972 // get the length of the unshift sequence from codecvt,
973 // without calling unshift.
974 const size_t __blen = 128;
975 char __buf[__blen];
976 codecvt_base::result __r;
977 streamsize __ilen = 0;
978
979 do
980 {
981 char* __next;
982 __r = _M_codecvt->unshift(_M_state_cur, __buf,
983 __buf + __blen, __next);
984 if (__r == codecvt_base::error)
985 __testvalid = false;
986 else if (__r == codecvt_base::ok ||
987 __r == codecvt_base::partial)
988 {
989 __ilen = __next - __buf;
990 if (__ilen > 0)
991 {
992 const streamsize __elen = _M_file.xsputn(__buf, __ilen);
993 if (__elen != __ilen)
994 __testvalid = false;
995 }
996 }
997 }
998 while (__r == codecvt_base::partial && __ilen > 0 && __testvalid);
999
1000 if (__testvalid)
1001 {
1002 // This second call to overflow() is required by the standard,
1003 // but it's not clear why it's needed, since the output buffer
1004 // should be empty by this point (it should have been emptied
1005 // in the first call to overflow()).
1006 const int_type __tmp = this->overflow();
1007 if (traits_type::eq_int_type(__tmp, traits_type::eof()))
1008 __testvalid = false;
1009 }
1010 }
1011 return __testvalid;
1012 }
1013
1014 template<typename _CharT, typename _Traits>
1015 int
1017 sync()
1018 {
1019 // Make sure that the internal buffer resyncs its idea of
1020 // the file position with the external file.
1021 int __ret = 0;
1022 if (this->pbase() < this->pptr())
1023 {
1024 const int_type __tmp = this->overflow();
1025 if (traits_type::eq_int_type(__tmp, traits_type::eof()))
1026 __ret = -1;
1027 }
1028 return __ret;
1029 }
1030
1031 template<typename _CharT, typename _Traits>
1032 void
1034 imbue(const locale& __loc)
1035 {
1036 bool __testvalid = true;
1037
1038 const __codecvt_type* const _M_codecvt_tmp
1039 = __try_use_facet<__codecvt_type>(__loc);
1040
1041 if (this->is_open())
1042 {
1043 // encoding() == -1 is ok only at the beginning.
1044 if ((_M_reading || _M_writing)
1045 && __check_facet(_M_codecvt).encoding() == -1)
1046 __testvalid = false;
1047 else
1048 {
1049 if (_M_reading)
1050 {
1051 if (__check_facet(_M_codecvt).always_noconv())
1052 {
1053 if (_M_codecvt_tmp
1054 && !__check_facet(_M_codecvt_tmp).always_noconv())
1055 __testvalid = this->seekoff(0, ios_base::cur, _M_mode)
1056 != pos_type(off_type(-1));
1057 }
1058 else
1059 {
1060 // External position corresponding to gptr().
1062 + _M_codecvt->length(_M_state_last, _M_ext_buf,
1064 this->gptr() - this->eback());
1065 const streamsize __remainder = _M_ext_end - _M_ext_next;
1066 if (__remainder)
1067 __builtin_memmove(_M_ext_buf, _M_ext_next, __remainder);
1068
1070 _M_ext_end = _M_ext_buf + __remainder;
1071 _M_set_buffer(-1);
1072 _M_state_last = _M_state_cur = _M_state_beg;
1073 }
1074 }
1075 else if (_M_writing && (__testvalid = _M_terminate_output()))
1076 _M_set_buffer(-1);
1077 }
1078 }
1079
1080 if (__testvalid)
1081 _M_codecvt = _M_codecvt_tmp;
1082 else
1083 _M_codecvt = 0;
1084 }
1085
1086 // Inhibit implicit instantiations for required instantiations,
1087 // which are defined via explicit instantiations elsewhere.
1088#if _GLIBCXX_EXTERN_TEMPLATE
1089 extern template class basic_filebuf<char>;
1090 extern template class basic_ifstream<char>;
1091 extern template class basic_ofstream<char>;
1092 extern template class basic_fstream<char>;
1093
1094#ifdef _GLIBCXX_USE_WCHAR_T
1095 extern template class basic_filebuf<wchar_t>;
1096 extern template class basic_ifstream<wchar_t>;
1097 extern template class basic_ofstream<wchar_t>;
1098 extern template class basic_fstream<wchar_t>;
1099#endif
1100#endif
1101
1102_GLIBCXX_END_NAMESPACE_VERSION
1103} // namespace std
1104
1105#endif
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition move.h:137
constexpr const _Tp & min(const _Tp &, const _Tp &)
This does what you think it does.
ISO C++ entities toplevel namespace is std.
ptrdiff_t streamsize
Integral type for I/O operation counts and buffer sizes.
Definition postypes.h:68
The actual work of input and output (for files).
Definition fstream:91
virtual pos_type seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode __mode=ios_base::in|ios_base::out)
Alters the stream positions.
Definition fstream.tcc:837
virtual int_type underflow()
Fetches more data from the controlled sequence.
Definition fstream.tcc:323
char_type _M_pback
Definition fstream:174
virtual streamsize showmanyc()
Investigating the data available.
Definition fstream.tcc:297
ios_base::openmode _M_mode
Place to stash in || out || in | out settings for current filebuf.
Definition fstream:131
streamsize _M_ext_buf_size
Definition fstream:193
char_type * _M_pback_cur_save
Definition fstream:175
virtual void imbue(const locale &__loc)
Changes translations.
Definition fstream.tcc:1034
virtual streamsize xsgetn(char_type *__s, streamsize __n)
Multiple character extraction.
Definition fstream.tcc:677
bool is_open() const
Returns true if the external file is open.
Definition fstream:275
size_t _M_buf_size
Definition fstream:153
__filebuf_type * close()
Closes the currently associated file.
Definition fstream.tcc:249
char_type * _M_pback_end_save
Definition fstream:176
char * _M_ext_buf
Definition fstream:188
void _M_destroy_pback()
Definition fstream:226
virtual pos_type seekpos(pos_type __pos, ios_base::openmode __mode=ios_base::in|ios_base::out)
Alters the stream positions.
Definition fstream.tcc:897
char_type * _M_buf
Pointer to the beginning of internal buffer.
Definition fstream:146
virtual int_type pbackfail(int_type __c=_Traits::eof())
Tries to back up the input sequence.
Definition fstream.tcc:482
virtual streamsize xsputn(const char_type *__s, streamsize __n)
Multiple character insertion.
Definition fstream.tcc:763
virtual int_type overflow(int_type __c=_Traits::eof())
Consumes data from the buffer; writes to the controlled sequence.
Definition fstream.tcc:541
void _M_create_pback()
Definition fstream:209
__filebuf_type * open(const char *__s, ios_base::openmode __mode)
Opens an external file.
Definition fstream.tcc:179
basic_filebuf()
Does not open any files.
Definition fstream.tcc:81
void _M_set_buffer(streamsize __off)
Definition fstream:499
virtual int sync()
Synchronizes the buffer arrays with the controlled sequences.
Definition fstream.tcc:1017
const char * _M_ext_next
Definition fstream:200
virtual __streambuf_type * setbuf(char_type *__s, streamsize __n)
Manipulates the buffer.
Definition fstream.tcc:808
Controlling input for files.
Definition fstream:533
Controlling output for files.
Definition fstream:803
Controlling input and output for files.
Definition fstream:1075
char_type * epptr() const
Access to the put area.
Definition streambuf:547
virtual streamsize xsputn(const char_type *__s, streamsize __n)
char_type * pptr() const
Access to the put area.
Definition streambuf:544
void setg(char_type *__gbeg, char_type *__gnext, char_type *__gend)
Setting the three read area pointers.
Definition streambuf:521
char_type * eback() const
Access to the get area.
Definition streambuf:489
char_type * egptr() const
Access to the get area.
Definition streambuf:499
char_type * gptr() const
Access to the get area.
Definition streambuf:496
virtual streamsize xsgetn(char_type *__s, streamsize __n)
void gbump(int __n)
Moving the read position.
Definition streambuf:509
void pbump(int __n)
Moving the write position.
Definition streambuf:557
char_type * pbase() const
Access to the put area.
Definition streambuf:541
locale _M_buf_locale
Current locale setting.
Definition streambuf:199
The base of the I/O class hierarchy.
Definition ios_base.h:255
static const seekdir cur
Request a seek relative to the current position within the sequence.
Definition ios_base.h:518
static const seekdir beg
Request a seek relative to the beginning of the stream.
Definition ios_base.h:515
static const seekdir end
Request a seek relative to the current end of the sequence.
Definition ios_base.h:521
static const openmode in
Open for input. Default for ifstream and fstream.
Definition ios_base.h:487
static const openmode out
Open for output. Default for ofstream and fstream.
Definition ios_base.h:490
static const openmode binary
Perform input and output in binary mode (as opposed to text mode). This is probably not what you thin...
Definition ios_base.h:484
_Ios_Openmode openmode
This is a bitmask type.
Definition ios_base.h:473
static const openmode app
Seek to end before each write.
Definition ios_base.h:476
_Ios_Seekdir seekdir
This is an enumerated type.
Definition ios_base.h:512
static const openmode ate
Open and seek to end immediately after opening.
Definition ios_base.h:479
Container class for localization functionality.