libstdc++
fstream
Go to the documentation of this file.
1// File based streams -*- C++ -*-
2
3// Copyright (C) 1997-2026 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 include/fstream
26 * This is a Standard C++ Library header.
27 */
28
29//
30// ISO C++ 14882: 27.8 File-based streams
31//
32
33#ifndef _GLIBCXX_FSTREAM
34#define _GLIBCXX_FSTREAM 1
35
36#ifdef _GLIBCXX_SYSHDR
37#pragma GCC system_header
38#endif
39
40#include <bits/requires_hosted.h> // iostreams
41
42#include <istream>
43#include <ostream>
44#include <bits/iosfwd_file.h>
45#include <bits/codecvt.h>
46#include <cstdio> // For BUFSIZ
47#include <bits/basic_file.h> // For __basic_file, __c_lock
48#if __cplusplus >= 201103L
49#include <string> // For std::string overloads.
50#endif
51
52#define __glibcxx_want_fstream_native_handle
53#include <bits/version.h>
54
55// This can be overridden by the target's os_defines.h
56#ifndef _GLIBCXX_BUFSIZ
57# define _GLIBCXX_BUFSIZ BUFSIZ
58#endif
59
60namespace std _GLIBCXX_VISIBILITY(default)
61{
62_GLIBCXX_BEGIN_NAMESPACE_VERSION
63
64#if __cplusplus >= 201703L
65 // Enable if _Path is a filesystem::path or experimental::filesystem::path
66 template<typename _Path, typename _Result = _Path, typename _Path2
67 = decltype(std::declval<_Path&>().make_preferred().filename())>
68 using _If_fs_path = enable_if_t<is_same_v<_Path, _Path2>, _Result>;
69#endif // C++17
70
71
72 // [27.8.1.1] template class basic_filebuf
73 /**
74 * @brief The actual work of input and output (for files).
75 * @ingroup io
76 *
77 * @tparam _CharT Type of character stream.
78 * @tparam _Traits Traits for character type, defaults to
79 * char_traits<_CharT>.
80 *
81 * This class associates both its input and output sequence with an
82 * external disk file, and maintains a joint file position for both
83 * sequences. Many of its semantics are described in terms of similar
84 * behavior in the Standard C Library's @c FILE streams.
85 *
86 * Requirements on traits_type, specific to this class:
87 * - traits_type::pos_type must be fpos<traits_type::state_type>
88 * - traits_type::off_type must be streamoff
89 * - traits_type::state_type must be Assignable and DefaultConstructible,
90 * - traits_type::state_type() must be the initial state for codecvt.
91 */
92 template<typename _CharT, typename _Traits>
93 class basic_filebuf : public basic_streambuf<_CharT, _Traits>
94 {
95#if __cplusplus >= 201103L
96 template<typename _Tp>
97 using __chk_state = __and_<is_copy_assignable<_Tp>,
100
101 static_assert(__chk_state<typename _Traits::state_type>::value,
102 "state_type must be CopyAssignable, CopyConstructible"
103 " and DefaultConstructible");
104
105 static_assert(is_same<typename _Traits::pos_type,
107 "pos_type must be fpos<state_type>");
108#endif
109 public:
110 // Types:
111 typedef _CharT char_type;
112 typedef _Traits traits_type;
113 typedef typename traits_type::int_type int_type;
114 typedef typename traits_type::pos_type pos_type;
115 typedef typename traits_type::off_type off_type;
116
117 typedef basic_streambuf<char_type, traits_type> __streambuf_type;
118 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
119 typedef __basic_file<char> __file_type;
120 typedef typename traits_type::state_type __state_type;
121 typedef codecvt<char_type, char, __state_type> __codecvt_type;
122
123 friend class ios_base; // For sync_with_stdio.
124
125 protected:
126 // Data Members:
127 // MT lock inherited from libio or other low-level io library.
128 __c_lock _M_lock;
129
130 // External buffer.
131 __file_type _M_file;
132
133 /// Place to stash in || out || in | out settings for current filebuf.
135
136 // Beginning state type for codecvt.
137 __state_type _M_state_beg;
138
139 // During output, the state that corresponds to pptr(),
140 // during input, the state that corresponds to egptr() and
141 // _M_ext_next.
142 __state_type _M_state_cur;
143
144 // Not used for output. During input, the state that corresponds
145 // to eback() and _M_ext_buf.
146 __state_type _M_state_last;
147
148 /// Pointer to the beginning of internal buffer.
149 char_type* _M_buf;
150
151 /**
152 * Actual size of internal buffer. This number is equal to the size
153 * of the put area + 1 position, reserved for the overflow char of
154 * a full area.
155 */
157
158 // Set iff _M_buf is allocated memory from _M_allocate_internal_buffer.
159 bool _M_buf_allocated;
160
161 /**
162 * _M_reading == false && _M_writing == false for @b uncommitted mode;
163 * _M_reading == true for @b read mode;
164 * _M_writing == true for @b write mode;
165 *
166 * NB: _M_reading == true && _M_writing == true is unused.
167 */
169 bool _M_writing;
170
171 ///@{
172 /**
173 * Necessary bits for putback buffer management.
174 *
175 * @note pbacks of over one character are not currently supported.
176 */
177 char_type _M_pback;
181 ///@}
182
183 // Cached codecvt facet.
184 const __codecvt_type* _M_codecvt;
185
186 /**
187 * Buffer for external characters. Used for input when
188 * codecvt::always_noconv() == false. When valid, this corresponds
189 * to eback().
190 */
192
193 /**
194 * Size of buffer held by _M_ext_buf.
195 */
197
198 /**
199 * Pointers into the buffer held by _M_ext_buf that delimit a
200 * subsequence of bytes that have been read but not yet converted.
201 * When valid, _M_ext_next corresponds to egptr().
202 */
203 const char* _M_ext_next;
204 char* _M_ext_end;
205
206 /**
207 * Initializes pback buffers, and moves normal buffers to safety.
208 * Assumptions:
209 * _M_in_cur has already been moved back
210 */
211 void
213 {
214 if (!_M_pback_init)
215 {
216 _M_pback_cur_save = this->gptr();
217 _M_pback_end_save = this->egptr();
218 this->setg(&_M_pback, &_M_pback, &_M_pback + 1);
219 _M_pback_init = true;
220 }
221 }
222
223 /**
224 * Deactivates pback buffer contents, and restores normal buffer.
225 * Assumptions:
226 * The pback buffer has only moved forward.
227 */
228 void
230 {
231 if (_M_pback_init)
232 {
233 // Length _M_in_cur moved in the pback buffer.
234 _M_pback_cur_save += this->gptr() != this->eback();
236 _M_pback_init = false;
237 }
238 }
239
240 public:
241 // Constructors/destructor:
242 /**
243 * @brief Does not open any files.
244 *
245 * The default constructor initializes the parent class using its
246 * own default ctor.
247 */
249
250#if __cplusplus >= 201103L
251 basic_filebuf(const basic_filebuf&) = delete;
253#endif
254
255 /**
256 * @brief The destructor closes the file first.
257 */
258 virtual
260 {
261 __try
262 { this->close(); }
263 __catch(...)
264 { }
265 }
266
267#if __cplusplus >= 201103L
268 basic_filebuf& operator=(const basic_filebuf&) = delete;
269 basic_filebuf& operator=(basic_filebuf&&);
270 void swap(basic_filebuf&);
271#endif
272
273 // Members:
274 /**
275 * @brief Returns true if the external file is open.
276 */
277 _GLIBCXX_NODISCARD
278 bool
279 is_open() const throw()
280 { return _M_file.is_open(); }
281
282 /**
283 * @brief Opens an external file.
284 * @param __s The name of the file.
285 * @param __mode The open mode flags.
286 * @return @c this on success, NULL on failure
287 *
288 * If a file is already open, this function immediately fails.
289 * Otherwise it tries to open the file named @a __s using the flags
290 * given in @a __mode.
291 *
292 * Table 92, adapted here, gives the relation between openmode
293 * combinations and the equivalent @c fopen() flags.
294 * (NB: lines app, in|out|app, in|app, binary|app, binary|in|out|app,
295 * and binary|in|app per DR 596)
296 * <pre>
297 * +---------------------------------------------------------+
298 * | ios_base Flag combination stdio equivalent |
299 * |binary in out trunc app |
300 * +---------------------------------------------------------+
301 * | + w |
302 * | + + a |
303 * | + a |
304 * | + + w |
305 * | + r |
306 * | + + r+ |
307 * | + + + w+ |
308 * | + + + a+ |
309 * | + + a+ |
310 * +---------------------------------------------------------+
311 * | + + wb |
312 * | + + + ab |
313 * | + + ab |
314 * | + + + wb |
315 * | + + rb |
316 * | + + + r+b |
317 * | + + + + w+b |
318 * | + + + + a+b |
319 * | + + + a+b |
320 * +---------------------------------------------------------+
321 * </pre>
322 */
323 __filebuf_type*
324 open(const char* __s, ios_base::openmode __mode);
325
326#if _GLIBCXX_HAVE__WFOPEN && _GLIBCXX_USE_WCHAR_T
327 /**
328 * @brief Opens an external file.
329 * @param __s The name of the file, as a wide character string.
330 * @param __mode The open mode flags.
331 * @return @c this on success, NULL on failure
332 */
333 __filebuf_type*
334 open(const wchar_t* __s, ios_base::openmode __mode);
335#endif
336
337#if __cplusplus >= 201103L
338 /**
339 * @brief Opens an external file.
340 * @param __s The name of the file.
341 * @param __mode The open mode flags.
342 * @return @c this on success, NULL on failure
343 */
344 __filebuf_type*
346 { return open(__s.c_str(), __mode); }
347
348#if __cplusplus >= 201703L
349 /**
350 * @brief Opens an external file.
351 * @param __s The name of the file, as a filesystem::path.
352 * @param __mode The open mode flags.
353 * @return @c this on success, NULL on failure
354 */
355 template<typename _Path>
356 _If_fs_path<_Path, __filebuf_type*>
357 open(const _Path& __s, ios_base::openmode __mode)
358 { return open(__s.c_str(), __mode); }
359#endif // C++17
360#endif // C++11
361
362 /**
363 * @brief Closes the currently associated file.
364 * @return @c this on success, NULL on failure
365 *
366 * If no file is currently open, this function immediately fails.
367 *
368 * If a <em>put buffer area</em> exists, @c overflow(eof) is
369 * called to flush all the characters. The file is then
370 * closed.
371 *
372 * If any operations fail, this function also fails.
373 */
374 __filebuf_type*
376
377#if __cpp_lib_fstream_native_handle // C++ >= 26
378 /**
379 * @brief The platform-specific file handle type.
380 *
381 * The type is `int` for POSIX platforms that use file descriptors,
382 * or `HANDLE` for Windows, or `FILE*` if the library was configured
383 * with `--enable-cstdio=stdio_pure`.
384 *
385 * @since C++26
386 */
387 using native_handle_type = typename __file_type::native_handle_type;
388
389 /**
390 * @brief Return the platform-specific native handle for the file.
391 * @pre `is_open()` is true.
392 * @return The native file handle associated with `*this`.
393 *
394 * The handle is invalidated when this filebuf is closed or destroyed.
395 *
396 * @since C++26
397 */
398 [[__gnu__::__always_inline__]]
399 native_handle_type
400 native_handle() const noexcept
401 {
402 __glibcxx_assert(is_open());
403 return _M_file.native_handle();
404 }
405#endif
406
407 protected:
408 void
409 _M_allocate_internal_buffer();
410
411 void
412 _M_destroy_internal_buffer() throw();
413
414 // [27.8.1.4] overridden virtual functions
415 virtual streamsize
417
418 // Stroustrup, 1998, p. 628
419 // underflow() and uflow() functions are called to get the next
420 // character from the real input source when the buffer is empty.
421 // Buffered input uses underflow()
422
423 virtual int_type
425
426 virtual int_type
427 pbackfail(int_type __c = _Traits::eof());
428
429 // Stroustrup, 1998, p 648
430 // The overflow() function is called to transfer characters to the
431 // real output destination when the buffer is full. A call to
432 // overflow(c) outputs the contents of the buffer plus the
433 // character c.
434 // 27.5.2.4.5
435 // Consume some sequence of the characters in the pending sequence.
436 virtual int_type
437 overflow(int_type __c = _Traits::eof());
438
439 // Convert internal byte sequence to external, char-based
440 // sequence via codecvt.
441 bool
442 _M_convert_to_external(char_type*, streamsize);
443
444 /**
445 * @brief Manipulates the buffer.
446 * @param __s Pointer to a buffer area.
447 * @param __n Size of @a __s.
448 * @return @c this
449 *
450 * If no file has been opened, and both @a __s and @a __n are zero, then
451 * the stream becomes unbuffered. Otherwise, @c __s is used as a
452 * buffer; see
453 * https://gcc.gnu.org/onlinedocs/libstdc++/manual/streambufs.html#io.streambuf.buffering
454 * for more.
455 */
456 virtual __streambuf_type*
457 setbuf(char_type* __s, streamsize __n);
458
459 virtual pos_type
460 seekoff(off_type __off, ios_base::seekdir __way,
461 ios_base::openmode __mode = ios_base::in | ios_base::out);
462
463 virtual pos_type
464 seekpos(pos_type __pos,
465 ios_base::openmode __mode = ios_base::in | ios_base::out);
466
467 // Common code for seekoff, seekpos, and overflow
468 pos_type
469 _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state);
470
471 int
472 _M_get_ext_pos(__state_type &__state);
473
474 virtual int
476
477 virtual void
478 imbue(const locale& __loc);
479
480 virtual streamsize
481 xsgetn(char_type* __s, streamsize __n);
482
483 virtual streamsize
484 xsputn(const char_type* __s, streamsize __n);
485
486 // Flushes output buffer, then writes unshift sequence.
487 bool
488 _M_terminate_output();
489
490 /**
491 * This function sets the pointers of the internal buffer, both get
492 * and put areas. Typically:
493 *
494 * __off == egptr() - eback() upon underflow/uflow (@b read mode);
495 * __off == 0 upon overflow (@b write mode);
496 * __off == -1 upon open, setbuf, seekoff/pos (@b uncommitted mode).
497 *
498 * NB: epptr() - pbase() == _M_buf_size - 1, since _M_buf_size
499 * reflects the actual allocated memory and the last cell is reserved
500 * for the overflow char of a full put area.
501 */
502 void
504 {
505 const bool __testin = _M_mode & ios_base::in;
506 const bool __testout = (_M_mode & ios_base::out
508
509 if (__testin && __off > 0)
510 this->setg(_M_buf, _M_buf, _M_buf + __off);
511 else
512 this->setg(_M_buf, _M_buf, _M_buf);
513
514 if (__testout && __off == 0 && _M_buf_size > 1 )
515 this->setp(_M_buf, _M_buf + _M_buf_size - 1);
516 else
517 this->setp(0, 0);
518 }
519 };
520
521 // [27.8.1.5] Template class basic_ifstream
522 /**
523 * @brief Controlling input for files.
524 * @ingroup io
525 *
526 * @tparam _CharT Type of character stream.
527 * @tparam _Traits Traits for character type, defaults to
528 * char_traits<_CharT>.
529 *
530 * This class supports reading from named files, using the inherited
531 * functions from std::basic_istream. To control the associated
532 * sequence, an instance of std::basic_filebuf is used, which this page
533 * refers to as @c sb.
534 */
535 template<typename _CharT, typename _Traits>
536 class basic_ifstream : public basic_istream<_CharT, _Traits>
537 {
538 public:
539 // Types:
540 typedef _CharT char_type;
541 typedef _Traits traits_type;
542 typedef typename traits_type::int_type int_type;
543 typedef typename traits_type::pos_type pos_type;
544 typedef typename traits_type::off_type off_type;
545
546 // Non-standard types:
547 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
548 typedef basic_istream<char_type, traits_type> __istream_type;
549
550 private:
551 __filebuf_type _M_filebuf;
552
553 public:
554 // Constructors/Destructors:
555 /**
556 * @brief Default constructor.
557 *
558 * Initializes @c sb using its default constructor, and passes
559 * @c &sb to the base class initializer. Does not open any files
560 * (you haven't given it a filename to open).
561 */
562 basic_ifstream() : __istream_type(), _M_filebuf()
563 { this->init(&_M_filebuf); }
564
565 /**
566 * @brief Create an input file stream.
567 * @param __s Null terminated string specifying the filename.
568 * @param __mode Open file in specified mode (see std::ios_base).
569 *
570 * @c ios_base::in is automatically included in @a __mode.
571 */
572 explicit
574 : __istream_type(), _M_filebuf()
575 {
576 this->init(&_M_filebuf);
577 this->open(__s, __mode);
578 }
579
580#if _GLIBCXX_HAVE__WFOPEN && _GLIBCXX_USE_WCHAR_T
581 /**
582 * @param Create an input file stream.
583 * @param __s Wide string specifying the filename.
584 * @param __mode Open file in specified mode (see std::ios_base).
585 *
586 * @c ios_base::in is automatically included in @a __mode.
587 */
588 basic_ifstream(const wchar_t* __s,
590 : __istream_type(), _M_filebuf()
591 {
592 this->init(&_M_filebuf);
593 this->open(__s, __mode);
594 }
595#endif
596
597#if __cplusplus >= 201103L
598 /**
599 * @brief Create an input file stream.
600 * @param __s std::string specifying the filename.
601 * @param __mode Open file in specified mode (see std::ios_base).
602 *
603 * @c ios_base::in is automatically included in @a __mode.
604 */
605 explicit
608 : __istream_type(), _M_filebuf()
609 {
610 this->init(&_M_filebuf);
611 this->open(__s, __mode);
612 }
613
614#if __cplusplus >= 201703L
615 /**
616 * @brief Create an input file stream.
617 * @param __s filesystem::path specifying the filename.
618 * @param __mode Open file in specified mode (see std::ios_base).
619 *
620 * @c ios_base::in is automatically included in @a __mode.
621 */
622 template<typename _Path, typename _Require = _If_fs_path<_Path>>
623 basic_ifstream(const _Path& __s,
625 : basic_ifstream(__s.c_str(), __mode)
626 { }
627#endif // C++17
628
629 basic_ifstream(const basic_ifstream&) = delete;
630
632 : __istream_type(std::move(__rhs)),
633 _M_filebuf(std::move(__rhs._M_filebuf))
634 { __istream_type::set_rdbuf(&_M_filebuf); }
635#endif // C++11
636
637 /**
638 * @brief The destructor does nothing.
639 *
640 * The file is closed by the filebuf object, not the formatting
641 * stream.
642 */
645
646#if __cplusplus >= 201103L
647 // 27.8.3.2 Assign and swap:
648
650 operator=(const basic_ifstream&) = delete;
651
653 operator=(basic_ifstream&& __rhs)
654 {
655 __istream_type::operator=(std::move(__rhs));
656 _M_filebuf = std::move(__rhs._M_filebuf);
657 return *this;
658 }
659
660 void
661 swap(basic_ifstream& __rhs)
662 {
663 __istream_type::swap(__rhs);
664 _M_filebuf.swap(__rhs._M_filebuf);
665 }
666#endif
667
668 // Members:
669 /**
670 * @brief Accessing the underlying buffer.
671 * @return The current basic_filebuf buffer.
672 *
673 * This hides both signatures of std::basic_ios::rdbuf().
674 */
675 _GLIBCXX_NODISCARD
676 __filebuf_type*
677 rdbuf() const
678 { return const_cast<__filebuf_type*>(&_M_filebuf); }
679
680 /**
681 * @brief Wrapper to test for an open file.
682 * @return @c rdbuf()->is_open()
683 */
684 _GLIBCXX_NODISCARD
685 bool
687 { return _M_filebuf.is_open(); }
688
689 // _GLIBCXX_RESOLVE_LIB_DEFECTS
690 // 365. Lack of const-qualification in clause 27
691 _GLIBCXX_NODISCARD
692 bool
693 is_open() const
694 { return _M_filebuf.is_open(); }
695
696 /**
697 * @brief Opens an external file.
698 * @param __s The name of the file.
699 * @param __mode The open mode flags.
700 *
701 * Calls @c std::basic_filebuf::open(s,__mode|in). If that function
702 * fails, @c failbit is set in the stream's error state.
703 */
704 void
705 open(const char* __s, ios_base::openmode __mode = ios_base::in)
706 {
707 if (!_M_filebuf.open(__s, __mode | ios_base::in))
709 else
710 // _GLIBCXX_RESOLVE_LIB_DEFECTS
711 // 409. Closing an fstream should clear error state
712 this->clear();
713 }
714
715#if _GLIBCXX_HAVE__WFOPEN && _GLIBCXX_USE_WCHAR_T
716 /**
717 * @brief Opens an external file.
718 * @param __s The name of the file, as a wide character string.
719 * @param __mode The open mode flags.
720 *
721 * Calls @c std::basic_filebuf::open(__s,__mode|in). If that function
722 * fails, @c failbit is set in the stream's error state.
723 */
724 void
725 open(const wchar_t* __s, ios_base::openmode __mode = ios_base::in)
726 {
727 if (!_M_filebuf.open(__s, __mode | ios_base::in))
729 else
730 this->clear();
731 }
732#endif
733
734#if __cplusplus >= 201103L
735 /**
736 * @brief Opens an external file.
737 * @param __s The name of the file.
738 * @param __mode The open mode flags.
739 *
740 * Calls @c std::basic_filebuf::open(__s,__mode|in). If that function
741 * fails, @c failbit is set in the stream's error state.
742 */
743 void
745 {
746 if (!_M_filebuf.open(__s, __mode | ios_base::in))
748 else
749 // _GLIBCXX_RESOLVE_LIB_DEFECTS
750 // 409. Closing an fstream should clear error state
751 this->clear();
752 }
753
754#if __cplusplus >= 201703L
755 /**
756 * @brief Opens an external file.
757 * @param __s The name of the file, as a filesystem::path.
758 * @param __mode The open mode flags.
759 *
760 * Calls @c std::basic_filebuf::open(__s,__mode|in). If that function
761 * fails, @c failbit is set in the stream's error state.
762 */
763 template<typename _Path>
764 _If_fs_path<_Path, void>
765 open(const _Path& __s, ios_base::openmode __mode = ios_base::in)
766 { open(__s.c_str(), __mode); }
767#endif // C++17
768#endif // C++11
769
770 /**
771 * @brief Close the file.
772 *
773 * Calls @c std::basic_filebuf::close(). If that function
774 * fails, @c failbit is set in the stream's error state.
775 */
776 void
778 {
779 if (!_M_filebuf.close())
781 }
782
783#if __cpp_lib_fstream_native_handle // C++ >= 26
784 using native_handle_type = typename __filebuf_type::native_handle_type;
785
786 [[__gnu__::__always_inline__]]
787 native_handle_type
788 native_handle() const noexcept
789 { return _M_filebuf.native_handle(); }
790#endif
791 };
792
793
794 // [27.8.1.8] Template class basic_ofstream
795 /**
796 * @brief Controlling output for files.
797 * @ingroup io
798 *
799 * @tparam _CharT Type of character stream.
800 * @tparam _Traits Traits for character type, defaults to
801 * char_traits<_CharT>.
802 *
803 * This class supports reading from named files, using the inherited
804 * functions from std::basic_ostream. To control the associated
805 * sequence, an instance of std::basic_filebuf is used, which this page
806 * refers to as @c sb.
807 */
808 template<typename _CharT, typename _Traits>
809 class basic_ofstream : public basic_ostream<_CharT,_Traits>
810 {
811 public:
812 // Types:
813 typedef _CharT char_type;
814 typedef _Traits traits_type;
815 typedef typename traits_type::int_type int_type;
816 typedef typename traits_type::pos_type pos_type;
817 typedef typename traits_type::off_type off_type;
818
819 // Non-standard types:
820 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
821 typedef basic_ostream<char_type, traits_type> __ostream_type;
822
823 private:
824 __filebuf_type _M_filebuf;
825
826 public:
827 // Constructors:
828 /**
829 * @brief Default constructor.
830 *
831 * Initializes @c sb using its default constructor, and passes
832 * @c &sb to the base class initializer. Does not open any files
833 * (you haven't given it a filename to open).
834 */
835 basic_ofstream(): __ostream_type(), _M_filebuf()
836 { this->init(&_M_filebuf); }
837
838 /**
839 * @brief Create an output file stream.
840 * @param __s Null terminated string specifying the filename.
841 * @param __mode Open file in specified mode (see std::ios_base).
842 *
843 * @c ios_base::out is automatically included in @a __mode.
844 */
845 explicit
846 basic_ofstream(const char* __s,
848 : __ostream_type(), _M_filebuf()
849 {
850 this->init(&_M_filebuf);
851 this->open(__s, __mode);
852 }
853
854#if _GLIBCXX_HAVE__WFOPEN && _GLIBCXX_USE_WCHAR_T
855 /**
856 * @param Create an output file stream.
857 * @param __s Wide string specifying the filename.
858 * @param __mode Open file in specified mode (see std::ios_base).
859 *
860 * @c ios_base::out | @c ios_base::trunc is automatically included in
861 * @a __mode.
862 */
863 basic_ofstream(const wchar_t* __s,
865 : __ostream_type(), _M_filebuf()
866 {
867 this->init(&_M_filebuf);
868 this->open(__s, __mode);
869 }
870#endif
871
872#if __cplusplus >= 201103L
873 /**
874 * @brief Create an output file stream.
875 * @param __s std::string specifying the filename.
876 * @param __mode Open file in specified mode (see std::ios_base).
877 *
878 * @c ios_base::out is automatically included in @a __mode.
879 */
880 explicit
883 : __ostream_type(), _M_filebuf()
884 {
885 this->init(&_M_filebuf);
886 this->open(__s, __mode);
887 }
888
889#if __cplusplus >= 201703L
890 /**
891 * @brief Create an output file stream.
892 * @param __s filesystem::path specifying the filename.
893 * @param __mode Open file in specified mode (see std::ios_base).
894 *
895 * @c ios_base::out is automatically included in @a __mode.
896 */
897 template<typename _Path, typename _Require = _If_fs_path<_Path>>
898 basic_ofstream(const _Path& __s,
900 : basic_ofstream(__s.c_str(), __mode)
901 { }
902#endif // C++17
903
904 basic_ofstream(const basic_ofstream&) = delete;
905
907 : __ostream_type(std::move(__rhs)),
908 _M_filebuf(std::move(__rhs._M_filebuf))
909 { __ostream_type::set_rdbuf(&_M_filebuf); }
910#endif
911
912 /**
913 * @brief The destructor does nothing.
914 *
915 * The file is closed by the filebuf object, not the formatting
916 * stream.
917 */
920
921#if __cplusplus >= 201103L
922 // 27.8.3.2 Assign and swap:
923
925 operator=(const basic_ofstream&) = delete;
926
928 operator=(basic_ofstream&& __rhs)
929 {
930 __ostream_type::operator=(std::move(__rhs));
931 _M_filebuf = std::move(__rhs._M_filebuf);
932 return *this;
933 }
934
935 void
936 swap(basic_ofstream& __rhs)
937 {
938 __ostream_type::swap(__rhs);
939 _M_filebuf.swap(__rhs._M_filebuf);
940 }
941#endif
942
943 // Members:
944 /**
945 * @brief Accessing the underlying buffer.
946 * @return The current basic_filebuf buffer.
947 *
948 * This hides both signatures of std::basic_ios::rdbuf().
949 */
950 _GLIBCXX_NODISCARD
951 __filebuf_type*
952 rdbuf() const
953 { return const_cast<__filebuf_type*>(&_M_filebuf); }
954
955 /**
956 * @brief Wrapper to test for an open file.
957 * @return @c rdbuf()->is_open()
958 */
959 _GLIBCXX_NODISCARD
960 bool
962 { return _M_filebuf.is_open(); }
963
964 // _GLIBCXX_RESOLVE_LIB_DEFECTS
965 // 365. Lack of const-qualification in clause 27
966 _GLIBCXX_NODISCARD
967 bool
968 is_open() const
969 { return _M_filebuf.is_open(); }
970
971 /**
972 * @brief Opens an external file.
973 * @param __s The name of the file.
974 * @param __mode The open mode flags.
975 *
976 * Calls @c std::basic_filebuf::open(__s,__mode|out). If that
977 * function fails, @c failbit is set in the stream's error state.
978 */
979 void
980 open(const char* __s, ios_base::openmode __mode = ios_base::out)
981 {
982 if (!_M_filebuf.open(__s, __mode | ios_base::out))
984 else
985 // _GLIBCXX_RESOLVE_LIB_DEFECTS
986 // 409. Closing an fstream should clear error state
987 this->clear();
988 }
989
990#if _GLIBCXX_HAVE__WFOPEN && _GLIBCXX_USE_WCHAR_T
991 /**
992 * @brief Opens an external file.
993 * @param __s The name of the file.
994 * @param __mode The open mode flags.
995 *
996 * Calls @c std::basic_filebuf::open(__s,__mode|out). If that
997 * function fails, @c failbit is set in the stream's error state.
998 */
999 void
1000 open(const wchar_t* __s, ios_base::openmode __mode = ios_base::out)
1001 {
1002 if (!_M_filebuf.open(__s, __mode | ios_base::out))
1004 else
1005 this->clear();
1006 }
1007#endif
1008
1009#if __cplusplus >= 201103L
1010 /**
1011 * @brief Opens an external file.
1012 * @param __s The name of the file.
1013 * @param __mode The open mode flags.
1014 *
1015 * Calls @c std::basic_filebuf::open(s,mode|out). If that
1016 * function fails, @c failbit is set in the stream's error state.
1017 */
1018 void
1020 {
1021 if (!_M_filebuf.open(__s, __mode | ios_base::out))
1023 else
1024 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1025 // 409. Closing an fstream should clear error state
1026 this->clear();
1027 }
1028
1029#if __cplusplus >= 201703L
1030 /**
1031 * @brief Opens an external file.
1032 * @param __s The name of the file, as a filesystem::path.
1033 * @param __mode The open mode flags.
1034 *
1035 * Calls @c std::basic_filebuf::open(__s,__mode|out). If that
1036 * function fails, @c failbit is set in the stream's error state.
1037 */
1038 template<typename _Path>
1039 _If_fs_path<_Path, void>
1040 open(const _Path& __s, ios_base::openmode __mode = ios_base::out)
1041 { open(__s.c_str(), __mode); }
1042#endif // C++17
1043#endif // C++11
1044
1045 /**
1046 * @brief Close the file.
1047 *
1048 * Calls @c std::basic_filebuf::close(). If that function
1049 * fails, @c failbit is set in the stream's error state.
1050 */
1051 void
1053 {
1054 if (!_M_filebuf.close())
1056 }
1057
1058#if __cpp_lib_fstream_native_handle // C++ >= 26
1059 using native_handle_type = typename __filebuf_type::native_handle_type;
1060
1061 [[__gnu__::__always_inline__]]
1062 native_handle_type
1063 native_handle() const noexcept
1064 { return _M_filebuf.native_handle(); }
1065#endif
1066 };
1067
1068
1069 // [27.8.1.11] Template class basic_fstream
1070 /**
1071 * @brief Controlling input and output for files.
1072 * @ingroup io
1073 *
1074 * @tparam _CharT Type of character stream.
1075 * @tparam _Traits Traits for character type, defaults to
1076 * char_traits<_CharT>.
1077 *
1078 * This class supports reading from and writing to named files, using
1079 * the inherited functions from std::basic_iostream. To control the
1080 * associated sequence, an instance of std::basic_filebuf is used, which
1081 * this page refers to as @c sb.
1082 */
1083 template<typename _CharT, typename _Traits>
1084 class basic_fstream : public basic_iostream<_CharT, _Traits>
1085 {
1086 public:
1087 // Types:
1088 typedef _CharT char_type;
1089 typedef _Traits traits_type;
1090 typedef typename traits_type::int_type int_type;
1091 typedef typename traits_type::pos_type pos_type;
1092 typedef typename traits_type::off_type off_type;
1093
1094 // Non-standard types:
1095 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
1096 typedef basic_ios<char_type, traits_type> __ios_type;
1097 typedef basic_iostream<char_type, traits_type> __iostream_type;
1098
1099 private:
1100 __filebuf_type _M_filebuf;
1101
1102 public:
1103 // Constructors/destructor:
1104 /**
1105 * @brief Default constructor.
1106 *
1107 * Initializes @c sb using its default constructor, and passes
1108 * @c &sb to the base class initializer. Does not open any files
1109 * (you haven't given it a filename to open).
1110 */
1112 : __iostream_type(), _M_filebuf()
1113 { this->init(&_M_filebuf); }
1114
1115 /**
1116 * @brief Create an input/output file stream.
1117 * @param __s Null terminated string specifying the filename.
1118 * @param __mode Open file in specified mode (see std::ios_base).
1119 */
1120 explicit
1121 basic_fstream(const char* __s,
1123 : __iostream_type(0), _M_filebuf()
1124 {
1125 this->init(&_M_filebuf);
1126 this->open(__s, __mode);
1127 }
1128
1129#if _GLIBCXX_HAVE__WFOPEN && _GLIBCXX_USE_WCHAR_T
1130 /**
1131 * @param Create an input/output file stream.
1132 * @param __s Wide string specifying the filename.
1133 * @param __mode Open file in specified mode (see std::ios_base).
1134 */
1135 basic_fstream(const wchar_t* __s,
1137 : __iostream_type(0), _M_filebuf()
1138 {
1139 this->init(&_M_filebuf);
1140 this->open(__s, __mode);
1141 }
1142#endif
1143
1144#if __cplusplus >= 201103L
1145 /**
1146 * @brief Create an input/output file stream.
1147 * @param __s Null terminated string specifying the filename.
1148 * @param __mode Open file in specified mode (see std::ios_base).
1149 */
1150 explicit
1153 : __iostream_type(0), _M_filebuf()
1154 {
1155 this->init(&_M_filebuf);
1156 this->open(__s, __mode);
1157 }
1158
1159#if __cplusplus >= 201703L
1160 /**
1161 * @brief Create an input/output file stream.
1162 * @param __s filesystem::path specifying the filename.
1163 * @param __mode Open file in specified mode (see std::ios_base).
1164 */
1165 template<typename _Path, typename _Require = _If_fs_path<_Path>>
1166 basic_fstream(const _Path& __s,
1168 : basic_fstream(__s.c_str(), __mode)
1169 { }
1170#endif // C++17
1171
1172 basic_fstream(const basic_fstream&) = delete;
1173
1175 : __iostream_type(std::move(__rhs)),
1176 _M_filebuf(std::move(__rhs._M_filebuf))
1177 { __iostream_type::set_rdbuf(&_M_filebuf); }
1178#endif
1179
1180 /**
1181 * @brief The destructor does nothing.
1182 *
1183 * The file is closed by the filebuf object, not the formatting
1184 * stream.
1185 */
1187 { }
1188
1189#if __cplusplus >= 201103L
1190 // 27.8.3.2 Assign and swap:
1191
1193 operator=(const basic_fstream&) = delete;
1194
1196 operator=(basic_fstream&& __rhs)
1197 {
1198 __iostream_type::operator=(std::move(__rhs));
1199 _M_filebuf = std::move(__rhs._M_filebuf);
1200 return *this;
1201 }
1202
1203 void
1204 swap(basic_fstream& __rhs)
1205 {
1206 __iostream_type::swap(__rhs);
1207 _M_filebuf.swap(__rhs._M_filebuf);
1208 }
1209#endif
1210
1211 // Members:
1212 /**
1213 * @brief Accessing the underlying buffer.
1214 * @return The current basic_filebuf buffer.
1215 *
1216 * This hides both signatures of std::basic_ios::rdbuf().
1217 */
1218 _GLIBCXX_NODISCARD
1219 __filebuf_type*
1220 rdbuf() const
1221 { return const_cast<__filebuf_type*>(&_M_filebuf); }
1222
1223 /**
1224 * @brief Wrapper to test for an open file.
1225 * @return @c rdbuf()->is_open()
1226 */
1227 _GLIBCXX_NODISCARD
1228 bool
1230 { return _M_filebuf.is_open(); }
1231
1232 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1233 // 365. Lack of const-qualification in clause 27
1234 _GLIBCXX_NODISCARD
1235 bool
1236 is_open() const
1237 { return _M_filebuf.is_open(); }
1238
1239 /**
1240 * @brief Opens an external file.
1241 * @param __s The name of the file.
1242 * @param __mode The open mode flags.
1243 *
1244 * Calls @c std::basic_filebuf::open(__s,__mode). If that
1245 * function fails, @c failbit is set in the stream's error state.
1246 */
1247 void
1248 open(const char* __s,
1250 {
1251 if (!_M_filebuf.open(__s, __mode))
1253 else
1254 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1255 // 409. Closing an fstream should clear error state
1256 this->clear();
1257 }
1258
1259#if _GLIBCXX_HAVE__WFOPEN && _GLIBCXX_USE_WCHAR_T
1260 /**
1261 * @brief Opens an external file.
1262 * @param __s The name of the file.
1263 * @param __mode The open mode flags.
1264 *
1265 * Calls @c std::basic_filebuf::open(__s,__mode). If that
1266 * function fails, @c failbit is set in the stream's error state.
1267 */
1268 void
1269 open(const wchar_t* __s,
1271 {
1272 if (!_M_filebuf.open(__s, __mode))
1274 else
1275 this->clear();
1276 }
1277#endif
1278
1279#if __cplusplus >= 201103L
1280 /**
1281 * @brief Opens an external file.
1282 * @param __s The name of the file.
1283 * @param __mode The open mode flags.
1284 *
1285 * Calls @c std::basic_filebuf::open(__s,__mode). If that
1286 * function fails, @c failbit is set in the stream's error state.
1287 */
1288 void
1289 open(const std::string& __s,
1291 {
1292 if (!_M_filebuf.open(__s, __mode))
1294 else
1295 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1296 // 409. Closing an fstream should clear error state
1297 this->clear();
1298 }
1299
1300#if __cplusplus >= 201703L
1301 /**
1302 * @brief Opens an external file.
1303 * @param __s The name of the file, as a filesystem::path.
1304 * @param __mode The open mode flags.
1305 *
1306 * Calls @c std::basic_filebuf::open(__s,__mode). If that
1307 * function fails, @c failbit is set in the stream's error state.
1308 */
1309 template<typename _Path>
1310 _If_fs_path<_Path, void>
1311 open(const _Path& __s,
1313 { open(__s.c_str(), __mode); }
1314#endif // C++17
1315#endif // C++11
1316
1317 /**
1318 * @brief Close the file.
1319 *
1320 * Calls @c std::basic_filebuf::close(). If that function
1321 * fails, @c failbit is set in the stream's error state.
1322 */
1323 void
1325 {
1326 if (!_M_filebuf.close())
1328 }
1329
1330#if __cpp_lib_fstream_native_handle // C++ >= 26
1331 using native_handle_type = typename __filebuf_type::native_handle_type;
1332
1333 [[__gnu__::__always_inline__]]
1334 native_handle_type
1335 native_handle() const noexcept
1336 { return _M_filebuf.native_handle(); }
1337#endif
1338 };
1339
1340#if __cplusplus >= 201103L
1341 /// Swap specialization for filebufs.
1342 template <class _CharT, class _Traits>
1343 inline void
1346 { __x.swap(__y); }
1347
1348 /// Swap specialization for ifstreams.
1349 template <class _CharT, class _Traits>
1350 inline void
1353 { __x.swap(__y); }
1354
1355 /// Swap specialization for ofstreams.
1356 template <class _CharT, class _Traits>
1357 inline void
1360 { __x.swap(__y); }
1361
1362 /// Swap specialization for fstreams.
1363 template <class _CharT, class _Traits>
1364 inline void
1367 { __x.swap(__y); }
1368#endif
1369
1370_GLIBCXX_END_NAMESPACE_VERSION
1371} // namespace
1372
1373#include <bits/fstream.tcc>
1374
1375#endif /* _GLIBCXX_FSTREAM */
typename enable_if< _Cond, _Tp >::type enable_if_t
Alias template for enable_if.
Definition type_traits:2967
auto declval() noexcept -> decltype(__declval< _Tp >(0))
Definition type_traits:2741
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition move.h:138
basic_string< char > string
A string of char.
Definition stringfwd.h:79
ISO C++ entities toplevel namespace is std.
ptrdiff_t streamsize
Integral type for I/O operation counts and buffer sizes.
Definition postypes.h:73
The actual work of input and output (for files).
Definition fstream:94
virtual pos_type seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode __mode=ios_base::in|ios_base::out)
virtual ~basic_filebuf()
The destructor closes the file first.
Definition fstream:259
_If_fs_path< _Path, __filebuf_type * > open(const _Path &__s, ios_base::openmode __mode)
Opens an external file.
Definition fstream:357
__filebuf_type * open(const std::string &__s, ios_base::openmode __mode)
Opens an external file.
Definition fstream:345
virtual void imbue(const locale &__loc)
virtual streamsize xsgetn(char_type *__s, streamsize __n)
bool is_open() const
Returns true if the external file is open.
Definition fstream:279
__filebuf_type * close()
Closes the currently associated file.
Definition fstream.tcc:254
void _M_destroy_pback()
Definition fstream:229
virtual pos_type seekpos(pos_type __pos, ios_base::openmode __mode=ios_base::in|ios_base::out)
virtual int_type pbackfail(int_type __c=traits_type::eof())
virtual streamsize xsputn(const char_type *__s, streamsize __n)
virtual int_type overflow(int_type __c=traits_type::eof())
void _M_create_pback()
Definition fstream:212
__filebuf_type * open(const char *__s, ios_base::openmode __mode)
Opens an external file.
Definition fstream.tcc:184
basic_filebuf()
Does not open any files.
Definition fstream.tcc:86
void _M_set_buffer(streamsize __off)
Definition fstream:503
virtual __streambuf_type * setbuf(char_type *__s, streamsize __n)
Controlling input for files.
Definition fstream:537
basic_ifstream()
Default constructor.
Definition fstream:562
~basic_ifstream()
The destructor does nothing.
Definition fstream:643
_If_fs_path< _Path, void > open(const _Path &__s, ios_base::openmode __mode=ios_base::in)
Opens an external file.
Definition fstream:765
__filebuf_type * rdbuf() const
Accessing the underlying buffer.
Definition fstream:677
void open(const char *__s, ios_base::openmode __mode=ios_base::in)
Opens an external file.
Definition fstream:705
basic_ifstream(const char *__s, ios_base::openmode __mode=ios_base::in)
Create an input file stream.
Definition fstream:573
void open(const std::string &__s, ios_base::openmode __mode=ios_base::in)
Opens an external file.
Definition fstream:744
basic_ifstream(const _Path &__s, ios_base::openmode __mode=ios_base::in)
Create an input file stream.
Definition fstream:623
basic_ifstream(const std::string &__s, ios_base::openmode __mode=ios_base::in)
Create an input file stream.
Definition fstream:606
void close()
Close the file.
Definition fstream:777
bool is_open()
Wrapper to test for an open file.
Definition fstream:686
Controlling output for files.
Definition fstream:810
basic_ofstream()
Default constructor.
Definition fstream:835
void open(const std::string &__s, ios_base::openmode __mode=ios_base::out)
Opens an external file.
Definition fstream:1019
basic_ofstream(const char *__s, ios_base::openmode __mode=ios_base::out)
Create an output file stream.
Definition fstream:846
void close()
Close the file.
Definition fstream:1052
basic_ofstream(const _Path &__s, ios_base::openmode __mode=ios_base::out)
Create an output file stream.
Definition fstream:898
__filebuf_type * rdbuf() const
Accessing the underlying buffer.
Definition fstream:952
void open(const char *__s, ios_base::openmode __mode=ios_base::out)
Opens an external file.
Definition fstream:980
basic_ofstream(const std::string &__s, ios_base::openmode __mode=ios_base::out)
Create an output file stream.
Definition fstream:881
~basic_ofstream()
The destructor does nothing.
Definition fstream:918
_If_fs_path< _Path, void > open(const _Path &__s, ios_base::openmode __mode=ios_base::out)
Opens an external file.
Definition fstream:1040
bool is_open()
Wrapper to test for an open file.
Definition fstream:961
Controlling input and output for files.
Definition fstream:1085
_If_fs_path< _Path, void > open(const _Path &__s, ios_base::openmode __mode=ios_base::in|ios_base::out)
Opens an external file.
Definition fstream:1311
~basic_fstream()
The destructor does nothing.
Definition fstream:1186
basic_fstream(const _Path &__s, ios_base::openmode __mode=ios_base::in|ios_base::out)
Create an input/output file stream.
Definition fstream:1166
void open(const char *__s, ios_base::openmode __mode=ios_base::in|ios_base::out)
Opens an external file.
Definition fstream:1248
basic_fstream(const std::string &__s, ios_base::openmode __mode=ios_base::in|ios_base::out)
Create an input/output file stream.
Definition fstream:1151
void open(const std::string &__s, ios_base::openmode __mode=ios_base::in|ios_base::out)
Opens an external file.
Definition fstream:1289
__filebuf_type * rdbuf() const
Accessing the underlying buffer.
Definition fstream:1220
bool is_open()
Wrapper to test for an open file.
Definition fstream:1229
void close()
Close the file.
Definition fstream:1324
basic_fstream(const char *__s, ios_base::openmode __mode=ios_base::in|ios_base::out)
Create an input/output file stream.
Definition fstream:1121
basic_fstream()
Default constructor.
Definition fstream:1111
basic_istream(__streambuf_type *__sb)
Base constructor.
Definition istream:107
basic_iostream(basic_streambuf< _CharT, _Traits > *__sb)
Constructor does nothing.
Definition istream:1027
void setg(char_type *__gbeg, char_type *__gnext, char_type *__gend)
Setting the three read area pointers.
Definition streambuf:518
char_type * eback() const
Access to the get area.
Definition streambuf:491
char_type * egptr() const
Access to the get area.
Definition streambuf:497
char_type * gptr() const
Access to the get area.
Definition streambuf:494
void setp(char_type *__pbeg, char_type *__pend)
Setting the three write area pointers.
Definition streambuf:564
basic_streambuf()
Base constructor.
Definition streambuf:472
is_default_constructible
Definition type_traits:1274
is_copy_constructible
Definition type_traits:1301
Template class basic_ios, virtual base class for all stream classes.
Definition basic_ios.h:71
void clear(iostate __state=goodbit)
[Re]sets the error state.
Definition basic_ios.tcc:46
void setstate(iostate __state)
Sets additional flags in the error state.
Definition basic_ios.h:167
void init(basic_streambuf< _CharT, _Traits > *__sb)
All setup is performed here.
constexpr const _CharT * c_str() const noexcept
Return const pointer to null-terminated contents.
Primary class template codecvt.
Definition codecvt.h:284
static const openmode in
Open for input. Default for ifstream and fstream.
Definition ios_base.h:498
static const openmode out
Open for output. Default for ofstream and fstream.
Definition ios_base.h:501
_Ios_Openmode openmode
This is a bitmask type.
Definition ios_base.h:484
static const openmode app
Seek to end before each write.
Definition ios_base.h:487
static const openmode trunc
Truncate an existing stream when opening. Default for ofstream.
Definition ios_base.h:504
static const iostate failbit
Indicates that an input operation failed to read the expected characters, or that an output operation...
Definition ios_base.h:465
basic_ostream(__streambuf_type *__sb)
Base constructor.
Definition ostream.h:97
Container class for localization functionality.
Class representing stream positions.
Definition postypes.h:88