1 // File based streams -*- C++ -*-
3 // Copyright (C) 1997-2014 Free Software Foundation, Inc.
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)
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.
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.
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/>.
25 /** @file include/fstream
26 * This is a Standard C++ Library header.
30 // ISO C++ 14882: 27.8 File-based streams
33 #ifndef _GLIBCXX_FSTREAM
34 #define _GLIBCXX_FSTREAM 1
36 #pragma GCC system_header
40 #include <bits/codecvt.h>
41 #include <cstdio> // For BUFSIZ
42 #include <bits/basic_file.h> // For __basic_file, __c_lock
43 #if __cplusplus >= 201103L
44 #include <string> // For std::string overloads.
47 namespace std _GLIBCXX_VISIBILITY(default)
49 _GLIBCXX_BEGIN_NAMESPACE_VERSION
51 // [27.8.1.1] template class basic_filebuf
53 * @brief The actual work of input and output (for files).
56 * @tparam _CharT Type of character stream.
57 * @tparam _Traits Traits for character type, defaults to
58 * char_traits<_CharT>.
60 * This class associates both its input and output sequence with an
61 * external disk file, and maintains a joint file position for both
62 * sequences. Many of its semantics are described in terms of similar
63 * behavior in the Standard C Library's @c FILE streams.
65 * Requirements on traits_type, specific to this class:
66 * - traits_type::pos_type must be fpos<traits_type::state_type>
67 * - traits_type::off_type must be streamoff
68 * - traits_type::state_type must be Assignable and DefaultConstructible,
69 * - traits_type::state_type() must be the initial state for codecvt.
71 template<typename _CharT, typename _Traits>
72 class basic_filebuf : public basic_streambuf<_CharT, _Traits>
74 #if __cplusplus >= 201103L
75 template<typename _Tp>
76 using __chk_state = __and_<is_copy_assignable<_Tp>,
77 is_copy_constructible<_Tp>,
78 is_default_constructible<_Tp>>;
80 static_assert(__chk_state<typename _Traits::state_type>::value,
81 "state_type must be CopyAssignable, CopyConstructible"
82 " and DefaultConstructible");
84 static_assert(is_same<typename _Traits::pos_type,
85 fpos<typename _Traits::state_type>>::value,
86 "pos_type must be fpos<state_type>");
90 typedef _CharT char_type;
91 typedef _Traits traits_type;
92 typedef typename traits_type::int_type int_type;
93 typedef typename traits_type::pos_type pos_type;
94 typedef typename traits_type::off_type off_type;
96 typedef basic_streambuf<char_type, traits_type> __streambuf_type;
97 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
98 typedef __basic_file<char> __file_type;
99 typedef typename traits_type::state_type __state_type;
100 typedef codecvt<char_type, char, __state_type> __codecvt_type;
102 friend class ios_base; // For sync_with_stdio.
106 // MT lock inherited from libio or other low-level io library.
112 /// Place to stash in || out || in | out settings for current filebuf.
113 ios_base::openmode _M_mode;
115 // Beginning state type for codecvt.
116 __state_type _M_state_beg;
118 // During output, the state that corresponds to pptr(),
119 // during input, the state that corresponds to egptr() and
121 __state_type _M_state_cur;
123 // Not used for output. During input, the state that corresponds
124 // to eback() and _M_ext_buf.
125 __state_type _M_state_last;
127 /// Pointer to the beginning of internal buffer.
131 * Actual size of internal buffer. This number is equal to the size
132 * of the put area + 1 position, reserved for the overflow char of
137 // Set iff _M_buf is allocated memory from _M_allocate_internal_buffer.
138 bool _M_buf_allocated;
141 * _M_reading == false && _M_writing == false for @b uncommitted mode;
142 * _M_reading == true for @b read mode;
143 * _M_writing == true for @b write mode;
145 * NB: _M_reading == true && _M_writing == true is unused.
152 * Necessary bits for putback buffer management.
154 * @note pbacks of over one character are not currently supported.
157 char_type* _M_pback_cur_save;
158 char_type* _M_pback_end_save;
162 // Cached codecvt facet.
163 const __codecvt_type* _M_codecvt;
166 * Buffer for external characters. Used for input when
167 * codecvt::always_noconv() == false. When valid, this corresponds
173 * Size of buffer held by _M_ext_buf.
175 streamsize _M_ext_buf_size;
178 * Pointers into the buffer held by _M_ext_buf that delimit a
179 * subsequence of bytes that have been read but not yet converted.
180 * When valid, _M_ext_next corresponds to egptr().
182 const char* _M_ext_next;
186 * Initializes pback buffers, and moves normal buffers to safety.
188 * _M_in_cur has already been moved back
195 _M_pback_cur_save = this->gptr();
196 _M_pback_end_save = this->egptr();
197 this->setg(&_M_pback, &_M_pback, &_M_pback + 1);
198 _M_pback_init = true;
203 * Deactivates pback buffer contents, and restores normal buffer.
205 * The pback buffer has only moved forward.
208 _M_destroy_pback() throw()
212 // Length _M_in_cur moved in the pback buffer.
213 _M_pback_cur_save += this->gptr() != this->eback();
214 this->setg(_M_buf, _M_pback_cur_save, _M_pback_end_save);
215 _M_pback_init = false;
220 // Constructors/destructor:
222 * @brief Does not open any files.
224 * The default constructor initializes the parent class using its
230 * @brief The destructor closes the file first.
238 * @brief Returns true if the external file is open.
241 is_open() const throw()
242 { return _M_file.is_open(); }
245 * @brief Opens an external file.
246 * @param __s The name of the file.
247 * @param __mode The open mode flags.
248 * @return @c this on success, NULL on failure
250 * If a file is already open, this function immediately fails.
251 * Otherwise it tries to open the file named @a __s using the flags
252 * given in @a __mode.
254 * Table 92, adapted here, gives the relation between openmode
255 * combinations and the equivalent @c fopen() flags.
256 * (NB: lines app, in|out|app, in|app, binary|app, binary|in|out|app,
257 * and binary|in|app per DR 596)
259 * +---------------------------------------------------------+
260 * | ios_base Flag combination stdio equivalent |
261 * |binary in out trunc app |
262 * +---------------------------------------------------------+
272 * +---------------------------------------------------------+
282 * +---------------------------------------------------------+
286 open(const char* __s, ios_base::openmode __mode);
288 #if __cplusplus >= 201103L
290 * @brief Opens an external file.
291 * @param __s The name of the file.
292 * @param __mode The open mode flags.
293 * @return @c this on success, NULL on failure
296 open(const std::string& __s, ios_base::openmode __mode)
297 { return open(__s.c_str(), __mode); }
301 * @brief Closes the currently associated file.
302 * @return @c this on success, NULL on failure
304 * If no file is currently open, this function immediately fails.
306 * If a <em>put buffer area</em> exists, @c overflow(eof) is
307 * called to flush all the characters. The file is then
310 * If any operations fail, this function also fails.
317 _M_allocate_internal_buffer();
320 _M_destroy_internal_buffer() throw();
322 // [27.8.1.4] overridden virtual functions
326 // Stroustrup, 1998, p. 628
327 // underflow() and uflow() functions are called to get the next
328 // character from the real input source when the buffer is empty.
329 // Buffered input uses underflow()
335 pbackfail(int_type __c = _Traits::eof());
337 // Stroustrup, 1998, p 648
338 // The overflow() function is called to transfer characters to the
339 // real output destination when the buffer is full. A call to
340 // overflow(c) outputs the contents of the buffer plus the
343 // Consume some sequence of the characters in the pending sequence.
345 overflow(int_type __c = _Traits::eof());
347 // Convert internal byte sequence to external, char-based
348 // sequence via codecvt.
350 _M_convert_to_external(char_type*, streamsize);
353 * @brief Manipulates the buffer.
354 * @param __s Pointer to a buffer area.
355 * @param __n Size of @a __s.
358 * If no file has been opened, and both @a __s and @a __n are zero, then
359 * the stream becomes unbuffered. Otherwise, @c __s is used as a
361 * https://gcc.gnu.org/onlinedocs/libstdc++/manual/streambufs.html#io.streambuf.buffering
364 virtual __streambuf_type*
365 setbuf(char_type* __s, streamsize __n);
368 seekoff(off_type __off, ios_base::seekdir __way,
369 ios_base::openmode __mode = ios_base::in | ios_base::out);
372 seekpos(pos_type __pos,
373 ios_base::openmode __mode = ios_base::in | ios_base::out);
375 // Common code for seekoff, seekpos, and overflow
377 _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state);
380 _M_get_ext_pos(__state_type &__state);
386 imbue(const locale& __loc);
389 xsgetn(char_type* __s, streamsize __n);
392 xsputn(const char_type* __s, streamsize __n);
394 // Flushes output buffer, then writes unshift sequence.
396 _M_terminate_output();
399 * This function sets the pointers of the internal buffer, both get
400 * and put areas. Typically:
402 * __off == egptr() - eback() upon underflow/uflow (@b read mode);
403 * __off == 0 upon overflow (@b write mode);
404 * __off == -1 upon open, setbuf, seekoff/pos (@b uncommitted mode).
406 * NB: epptr() - pbase() == _M_buf_size - 1, since _M_buf_size
407 * reflects the actual allocated memory and the last cell is reserved
408 * for the overflow char of a full put area.
411 _M_set_buffer(streamsize __off)
413 const bool __testin = _M_mode & ios_base::in;
414 const bool __testout = (_M_mode & ios_base::out
415 || _M_mode & ios_base::app);
417 if (__testin && __off > 0)
418 this->setg(_M_buf, _M_buf, _M_buf + __off);
420 this->setg(_M_buf, _M_buf, _M_buf);
422 if (__testout && __off == 0 && _M_buf_size > 1 )
423 this->setp(_M_buf, _M_buf + _M_buf_size - 1);
429 // [27.8.1.5] Template class basic_ifstream
431 * @brief Controlling input for files.
434 * @tparam _CharT Type of character stream.
435 * @tparam _Traits Traits for character type, defaults to
436 * char_traits<_CharT>.
438 * This class supports reading from named files, using the inherited
439 * functions from std::basic_istream. To control the associated
440 * sequence, an instance of std::basic_filebuf is used, which this page
441 * refers to as @c sb.
443 template<typename _CharT, typename _Traits>
444 class basic_ifstream : public basic_istream<_CharT, _Traits>
448 typedef _CharT char_type;
449 typedef _Traits traits_type;
450 typedef typename traits_type::int_type int_type;
451 typedef typename traits_type::pos_type pos_type;
452 typedef typename traits_type::off_type off_type;
454 // Non-standard types:
455 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
456 typedef basic_istream<char_type, traits_type> __istream_type;
459 __filebuf_type _M_filebuf;
462 // Constructors/Destructors:
464 * @brief Default constructor.
466 * Initializes @c sb using its default constructor, and passes
467 * @c &sb to the base class initializer. Does not open any files
468 * (you haven't given it a filename to open).
470 basic_ifstream() : __istream_type(), _M_filebuf()
471 { this->init(&_M_filebuf); }
474 * @brief Create an input file stream.
475 * @param __s Null terminated string specifying the filename.
476 * @param __mode Open file in specified mode (see std::ios_base).
478 * @c ios_base::in is automatically included in @a __mode.
480 * Tip: When using std::string to hold the filename, you must use
481 * .c_str() before passing it to this constructor.
484 basic_ifstream(const char* __s, ios_base::openmode __mode = ios_base::in)
485 : __istream_type(), _M_filebuf()
487 this->init(&_M_filebuf);
488 this->open(__s, __mode);
491 #if __cplusplus >= 201103L
493 * @brief Create an input file stream.
494 * @param __s std::string specifying the filename.
495 * @param __mode Open file in specified mode (see std::ios_base).
497 * @c ios_base::in is automatically included in @a __mode.
500 basic_ifstream(const std::string& __s,
501 ios_base::openmode __mode = ios_base::in)
502 : __istream_type(), _M_filebuf()
504 this->init(&_M_filebuf);
505 this->open(__s, __mode);
510 * @brief The destructor does nothing.
512 * The file is closed by the filebuf object, not the formatting
520 * @brief Accessing the underlying buffer.
521 * @return The current basic_filebuf buffer.
523 * This hides both signatures of std::basic_ios::rdbuf().
527 { return const_cast<__filebuf_type*>(&_M_filebuf); }
530 * @brief Wrapper to test for an open file.
531 * @return @c rdbuf()->is_open()
535 { return _M_filebuf.is_open(); }
537 // _GLIBCXX_RESOLVE_LIB_DEFECTS
538 // 365. Lack of const-qualification in clause 27
541 { return _M_filebuf.is_open(); }
544 * @brief Opens an external file.
545 * @param __s The name of the file.
546 * @param __mode The open mode flags.
548 * Calls @c std::basic_filebuf::open(s,__mode|in). If that function
549 * fails, @c failbit is set in the stream's error state.
551 * Tip: When using std::string to hold the filename, you must use
552 * .c_str() before passing it to this constructor.
555 open(const char* __s, ios_base::openmode __mode = ios_base::in)
557 if (!_M_filebuf.open(__s, __mode | ios_base::in))
558 this->setstate(ios_base::failbit);
560 // _GLIBCXX_RESOLVE_LIB_DEFECTS
561 // 409. Closing an fstream should clear error state
565 #if __cplusplus >= 201103L
567 * @brief Opens an external file.
568 * @param __s The name of the file.
569 * @param __mode The open mode flags.
571 * Calls @c std::basic_filebuf::open(__s,__mode|in). If that function
572 * fails, @c failbit is set in the stream's error state.
575 open(const std::string& __s, ios_base::openmode __mode = ios_base::in)
577 if (!_M_filebuf.open(__s, __mode | ios_base::in))
578 this->setstate(ios_base::failbit);
580 // _GLIBCXX_RESOLVE_LIB_DEFECTS
581 // 409. Closing an fstream should clear error state
587 * @brief Close the file.
589 * Calls @c std::basic_filebuf::close(). If that function
590 * fails, @c failbit is set in the stream's error state.
595 if (!_M_filebuf.close())
596 this->setstate(ios_base::failbit);
601 // [27.8.1.8] Template class basic_ofstream
603 * @brief Controlling output for files.
606 * @tparam _CharT Type of character stream.
607 * @tparam _Traits Traits for character type, defaults to
608 * char_traits<_CharT>.
610 * This class supports reading from named files, using the inherited
611 * functions from std::basic_ostream. To control the associated
612 * sequence, an instance of std::basic_filebuf is used, which this page
613 * refers to as @c sb.
615 template<typename _CharT, typename _Traits>
616 class basic_ofstream : public basic_ostream<_CharT,_Traits>
620 typedef _CharT char_type;
621 typedef _Traits traits_type;
622 typedef typename traits_type::int_type int_type;
623 typedef typename traits_type::pos_type pos_type;
624 typedef typename traits_type::off_type off_type;
626 // Non-standard types:
627 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
628 typedef basic_ostream<char_type, traits_type> __ostream_type;
631 __filebuf_type _M_filebuf;
636 * @brief Default constructor.
638 * Initializes @c sb using its default constructor, and passes
639 * @c &sb to the base class initializer. Does not open any files
640 * (you haven't given it a filename to open).
642 basic_ofstream(): __ostream_type(), _M_filebuf()
643 { this->init(&_M_filebuf); }
646 * @brief Create an output file stream.
647 * @param __s Null terminated string specifying the filename.
648 * @param __mode Open file in specified mode (see std::ios_base).
650 * @c ios_base::out | @c ios_base::trunc is automatically included in
653 * Tip: When using std::string to hold the filename, you must use
654 * .c_str() before passing it to this constructor.
657 basic_ofstream(const char* __s,
658 ios_base::openmode __mode = ios_base::out|ios_base::trunc)
659 : __ostream_type(), _M_filebuf()
661 this->init(&_M_filebuf);
662 this->open(__s, __mode);
665 #if __cplusplus >= 201103L
667 * @brief Create an output file stream.
668 * @param __s std::string specifying the filename.
669 * @param __mode Open file in specified mode (see std::ios_base).
671 * @c ios_base::out | @c ios_base::trunc is automatically included in
675 basic_ofstream(const std::string& __s,
676 ios_base::openmode __mode = ios_base::out|ios_base::trunc)
677 : __ostream_type(), _M_filebuf()
679 this->init(&_M_filebuf);
680 this->open(__s, __mode);
685 * @brief The destructor does nothing.
687 * The file is closed by the filebuf object, not the formatting
695 * @brief Accessing the underlying buffer.
696 * @return The current basic_filebuf buffer.
698 * This hides both signatures of std::basic_ios::rdbuf().
702 { return const_cast<__filebuf_type*>(&_M_filebuf); }
705 * @brief Wrapper to test for an open file.
706 * @return @c rdbuf()->is_open()
710 { return _M_filebuf.is_open(); }
712 // _GLIBCXX_RESOLVE_LIB_DEFECTS
713 // 365. Lack of const-qualification in clause 27
716 { return _M_filebuf.is_open(); }
719 * @brief Opens an external file.
720 * @param __s The name of the file.
721 * @param __mode The open mode flags.
723 * Calls @c std::basic_filebuf::open(__s,__mode|out|trunc). If that
724 * function fails, @c failbit is set in the stream's error state.
726 * Tip: When using std::string to hold the filename, you must use
727 * .c_str() before passing it to this constructor.
730 open(const char* __s,
731 ios_base::openmode __mode = ios_base::out | ios_base::trunc)
733 if (!_M_filebuf.open(__s, __mode | ios_base::out))
734 this->setstate(ios_base::failbit);
736 // _GLIBCXX_RESOLVE_LIB_DEFECTS
737 // 409. Closing an fstream should clear error state
741 #if __cplusplus >= 201103L
743 * @brief Opens an external file.
744 * @param __s The name of the file.
745 * @param __mode The open mode flags.
747 * Calls @c std::basic_filebuf::open(s,mode|out|trunc). If that
748 * function fails, @c failbit is set in the stream's error state.
751 open(const std::string& __s,
752 ios_base::openmode __mode = ios_base::out | ios_base::trunc)
754 if (!_M_filebuf.open(__s, __mode | ios_base::out))
755 this->setstate(ios_base::failbit);
757 // _GLIBCXX_RESOLVE_LIB_DEFECTS
758 // 409. Closing an fstream should clear error state
764 * @brief Close the file.
766 * Calls @c std::basic_filebuf::close(). If that function
767 * fails, @c failbit is set in the stream's error state.
772 if (!_M_filebuf.close())
773 this->setstate(ios_base::failbit);
778 // [27.8.1.11] Template class basic_fstream
780 * @brief Controlling input and output for files.
783 * @tparam _CharT Type of character stream.
784 * @tparam _Traits Traits for character type, defaults to
785 * char_traits<_CharT>.
787 * This class supports reading from and writing to named files, using
788 * the inherited functions from std::basic_iostream. To control the
789 * associated sequence, an instance of std::basic_filebuf is used, which
790 * this page refers to as @c sb.
792 template<typename _CharT, typename _Traits>
793 class basic_fstream : public basic_iostream<_CharT, _Traits>
797 typedef _CharT char_type;
798 typedef _Traits traits_type;
799 typedef typename traits_type::int_type int_type;
800 typedef typename traits_type::pos_type pos_type;
801 typedef typename traits_type::off_type off_type;
803 // Non-standard types:
804 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
805 typedef basic_ios<char_type, traits_type> __ios_type;
806 typedef basic_iostream<char_type, traits_type> __iostream_type;
809 __filebuf_type _M_filebuf;
812 // Constructors/destructor:
814 * @brief Default constructor.
816 * Initializes @c sb using its default constructor, and passes
817 * @c &sb to the base class initializer. Does not open any files
818 * (you haven't given it a filename to open).
821 : __iostream_type(), _M_filebuf()
822 { this->init(&_M_filebuf); }
825 * @brief Create an input/output file stream.
826 * @param __s Null terminated string specifying the filename.
827 * @param __mode Open file in specified mode (see std::ios_base).
829 * Tip: When using std::string to hold the filename, you must use
830 * .c_str() before passing it to this constructor.
833 basic_fstream(const char* __s,
834 ios_base::openmode __mode = ios_base::in | ios_base::out)
835 : __iostream_type(0), _M_filebuf()
837 this->init(&_M_filebuf);
838 this->open(__s, __mode);
841 #if __cplusplus >= 201103L
843 * @brief Create an input/output file stream.
844 * @param __s Null terminated string specifying the filename.
845 * @param __mode Open file in specified mode (see std::ios_base).
848 basic_fstream(const std::string& __s,
849 ios_base::openmode __mode = ios_base::in | ios_base::out)
850 : __iostream_type(0), _M_filebuf()
852 this->init(&_M_filebuf);
853 this->open(__s, __mode);
858 * @brief The destructor does nothing.
860 * The file is closed by the filebuf object, not the formatting
868 * @brief Accessing the underlying buffer.
869 * @return The current basic_filebuf buffer.
871 * This hides both signatures of std::basic_ios::rdbuf().
875 { return const_cast<__filebuf_type*>(&_M_filebuf); }
878 * @brief Wrapper to test for an open file.
879 * @return @c rdbuf()->is_open()
883 { return _M_filebuf.is_open(); }
885 // _GLIBCXX_RESOLVE_LIB_DEFECTS
886 // 365. Lack of const-qualification in clause 27
889 { return _M_filebuf.is_open(); }
892 * @brief Opens an external file.
893 * @param __s The name of the file.
894 * @param __mode The open mode flags.
896 * Calls @c std::basic_filebuf::open(__s,__mode). If that
897 * function fails, @c failbit is set in the stream's error state.
899 * Tip: When using std::string to hold the filename, you must use
900 * .c_str() before passing it to this constructor.
903 open(const char* __s,
904 ios_base::openmode __mode = ios_base::in | ios_base::out)
906 if (!_M_filebuf.open(__s, __mode))
907 this->setstate(ios_base::failbit);
909 // _GLIBCXX_RESOLVE_LIB_DEFECTS
910 // 409. Closing an fstream should clear error state
914 #if __cplusplus >= 201103L
916 * @brief Opens an external file.
917 * @param __s The name of the file.
918 * @param __mode The open mode flags.
920 * Calls @c std::basic_filebuf::open(__s,__mode). If that
921 * function fails, @c failbit is set in the stream's error state.
924 open(const std::string& __s,
925 ios_base::openmode __mode = ios_base::in | ios_base::out)
927 if (!_M_filebuf.open(__s, __mode))
928 this->setstate(ios_base::failbit);
930 // _GLIBCXX_RESOLVE_LIB_DEFECTS
931 // 409. Closing an fstream should clear error state
937 * @brief Close the file.
939 * Calls @c std::basic_filebuf::close(). If that function
940 * fails, @c failbit is set in the stream's error state.
945 if (!_M_filebuf.close())
946 this->setstate(ios_base::failbit);
950 _GLIBCXX_END_NAMESPACE_VERSION
953 #include <bits/fstream.tcc>
955 #endif /* _GLIBCXX_FSTREAM */