1 // File based streams -*- C++ -*-
3 // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4 // 2006, 2007, 2008, 2009, 2010, 2011, 2012
5 // Free Software Foundation, Inc.
7 // This file is part of the GNU ISO C++ Library. This library is free
8 // software; you can redistribute it and/or modify it under the
9 // terms of the GNU General Public License as published by the
10 // Free Software Foundation; either version 3, or (at your option)
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
18 // Under Section 7 of GPL version 3, you are granted additional
19 // permissions described in the GCC Runtime Library Exception, version
20 // 3.1, as published by the Free Software Foundation.
22 // You should have received a copy of the GNU General Public License and
23 // a copy of the GCC Runtime Library Exception along with this program;
24 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
25 // <http://www.gnu.org/licenses/>.
27 /** @file include/fstream
28 * This is a Standard C++ Library header.
32 // ISO C++ 14882: 27.8 File-based streams
35 #ifndef _GLIBCXX_FSTREAM
36 #define _GLIBCXX_FSTREAM 1
38 #pragma GCC system_header
42 #include <bits/codecvt.h>
43 #include <cstdio> // For BUFSIZ
44 #include <bits/basic_file.h> // For __basic_file, __c_lock
45 #if __cplusplus >= 201103L
46 #include <string> // For std::string overloads.
49 namespace std _GLIBCXX_VISIBILITY(default)
51 _GLIBCXX_BEGIN_NAMESPACE_VERSION
53 // [27.8.1.1] template class basic_filebuf
55 * @brief The actual work of input and output (for files).
58 * @tparam _CharT Type of character stream.
59 * @tparam _Traits Traits for character type, defaults to
60 * char_traits<_CharT>.
62 * This class associates both its input and output sequence with an
63 * external disk file, and maintains a joint file position for both
64 * sequences. Many of its semantics are described in terms of similar
65 * behavior in the Standard C Library's @c FILE streams.
67 * Requirements on traits_type, specific to this class:
68 * - traits_type::pos_type must be fpos<traits_type::state_type>
69 * - traits_type::off_type must be streamoff
70 * - traits_type::state_type must be Assignable and DefaultConstructible,
71 * - traits_type::state_type() must be the initial state for codecvt.
73 template<typename _CharT, typename _Traits>
74 class basic_filebuf : public basic_streambuf<_CharT, _Traits>
78 typedef _CharT char_type;
79 typedef _Traits traits_type;
80 typedef typename traits_type::int_type int_type;
81 typedef typename traits_type::pos_type pos_type;
82 typedef typename traits_type::off_type off_type;
84 typedef basic_streambuf<char_type, traits_type> __streambuf_type;
85 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
86 typedef __basic_file<char> __file_type;
87 typedef typename traits_type::state_type __state_type;
88 typedef codecvt<char_type, char, __state_type> __codecvt_type;
90 friend class ios_base; // For sync_with_stdio.
94 // MT lock inherited from libio or other low-level io library.
100 /// Place to stash in || out || in | out settings for current filebuf.
101 ios_base::openmode _M_mode;
103 // Beginning state type for codecvt.
104 __state_type _M_state_beg;
106 // During output, the state that corresponds to pptr(),
107 // during input, the state that corresponds to egptr() and
109 __state_type _M_state_cur;
111 // Not used for output. During input, the state that corresponds
112 // to eback() and _M_ext_buf.
113 __state_type _M_state_last;
115 /// Pointer to the beginning of internal buffer.
119 * Actual size of internal buffer. This number is equal to the size
120 * of the put area + 1 position, reserved for the overflow char of
125 // Set iff _M_buf is allocated memory from _M_allocate_internal_buffer.
126 bool _M_buf_allocated;
129 * _M_reading == false && _M_writing == false for @b uncommitted mode;
130 * _M_reading == true for @b read mode;
131 * _M_writing == true for @b write mode;
133 * NB: _M_reading == true && _M_writing == true is unused.
140 * Necessary bits for putback buffer management.
142 * @note pbacks of over one character are not currently supported.
145 char_type* _M_pback_cur_save;
146 char_type* _M_pback_end_save;
150 // Cached codecvt facet.
151 const __codecvt_type* _M_codecvt;
154 * Buffer for external characters. Used for input when
155 * codecvt::always_noconv() == false. When valid, this corresponds
161 * Size of buffer held by _M_ext_buf.
163 streamsize _M_ext_buf_size;
166 * Pointers into the buffer held by _M_ext_buf that delimit a
167 * subsequence of bytes that have been read but not yet converted.
168 * When valid, _M_ext_next corresponds to egptr().
170 const char* _M_ext_next;
174 * Initializes pback buffers, and moves normal buffers to safety.
176 * _M_in_cur has already been moved back
183 _M_pback_cur_save = this->gptr();
184 _M_pback_end_save = this->egptr();
185 this->setg(&_M_pback, &_M_pback, &_M_pback + 1);
186 _M_pback_init = true;
191 * Deactivates pback buffer contents, and restores normal buffer.
193 * The pback buffer has only moved forward.
196 _M_destroy_pback() throw()
200 // Length _M_in_cur moved in the pback buffer.
201 _M_pback_cur_save += this->gptr() != this->eback();
202 this->setg(_M_buf, _M_pback_cur_save, _M_pback_end_save);
203 _M_pback_init = false;
208 // Constructors/destructor:
210 * @brief Does not open any files.
212 * The default constructor initializes the parent class using its
218 * @brief The destructor closes the file first.
226 * @brief Returns true if the external file is open.
229 is_open() const throw()
230 { return _M_file.is_open(); }
233 * @brief Opens an external file.
234 * @param __s The name of the file.
235 * @param __mode The open mode flags.
236 * @return @c this on success, NULL on failure
238 * If a file is already open, this function immediately fails.
239 * Otherwise it tries to open the file named @a __s using the flags
240 * given in @a __mode.
242 * Table 92, adapted here, gives the relation between openmode
243 * combinations and the equivalent fopen() flags.
244 * (NB: lines app, in|out|app, in|app, binary|app, binary|in|out|app,
245 * and binary|in|app per DR 596)
246 * +---------------------------------------------------------+
247 * | ios_base Flag combination stdio equivalent |
248 * |binary in out trunc app |
249 * +---------------------------------------------------------+
259 * +---------------------------------------------------------+
269 * +---------------------------------------------------------+
272 open(const char* __s, ios_base::openmode __mode);
274 #if __cplusplus >= 201103L
276 * @brief Opens an external file.
277 * @param __s The name of the file.
278 * @param __mode The open mode flags.
279 * @return @c this on success, NULL on failure
282 open(const std::string& __s, ios_base::openmode __mode)
283 { return open(__s.c_str(), __mode); }
287 * @brief Closes the currently associated file.
288 * @return @c this on success, NULL on failure
290 * If no file is currently open, this function immediately fails.
292 * If a <em>put buffer area</em> exists, @c overflow(eof) is
293 * called to flush all the characters. The file is then
296 * If any operations fail, this function also fails.
303 _M_allocate_internal_buffer();
306 _M_destroy_internal_buffer() throw();
308 // [27.8.1.4] overridden virtual functions
312 // Stroustrup, 1998, p. 628
313 // underflow() and uflow() functions are called to get the next
314 // character from the real input source when the buffer is empty.
315 // Buffered input uses underflow()
321 pbackfail(int_type __c = _Traits::eof());
323 // Stroustrup, 1998, p 648
324 // The overflow() function is called to transfer characters to the
325 // real output destination when the buffer is full. A call to
326 // overflow(c) outputs the contents of the buffer plus the
329 // Consume some sequence of the characters in the pending sequence.
331 overflow(int_type __c = _Traits::eof());
333 // Convert internal byte sequence to external, char-based
334 // sequence via codecvt.
336 _M_convert_to_external(char_type*, streamsize);
339 * @brief Manipulates the buffer.
340 * @param __s Pointer to a buffer area.
341 * @param __n Size of @a __s.
344 * If no file has been opened, and both @a __s and @a __n are zero, then
345 * the stream becomes unbuffered. Otherwise, @c __s is used as a
347 * http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt11ch25s02.html
350 virtual __streambuf_type*
351 setbuf(char_type* __s, streamsize __n);
354 seekoff(off_type __off, ios_base::seekdir __way,
355 ios_base::openmode __mode = ios_base::in | ios_base::out);
358 seekpos(pos_type __pos,
359 ios_base::openmode __mode = ios_base::in | ios_base::out);
361 // Common code for seekoff, seekpos, and overflow
363 _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state);
366 _M_get_ext_pos(__state_type &__state);
372 imbue(const locale& __loc);
375 xsgetn(char_type* __s, streamsize __n);
378 xsputn(const char_type* __s, streamsize __n);
380 // Flushes output buffer, then writes unshift sequence.
382 _M_terminate_output();
385 * This function sets the pointers of the internal buffer, both get
386 * and put areas. Typically:
388 * __off == egptr() - eback() upon underflow/uflow (@b read mode);
389 * __off == 0 upon overflow (@b write mode);
390 * __off == -1 upon open, setbuf, seekoff/pos (@b uncommitted mode).
392 * NB: epptr() - pbase() == _M_buf_size - 1, since _M_buf_size
393 * reflects the actual allocated memory and the last cell is reserved
394 * for the overflow char of a full put area.
397 _M_set_buffer(streamsize __off)
399 const bool __testin = _M_mode & ios_base::in;
400 const bool __testout = _M_mode & ios_base::out;
402 if (__testin && __off > 0)
403 this->setg(_M_buf, _M_buf, _M_buf + __off);
405 this->setg(_M_buf, _M_buf, _M_buf);
407 if (__testout && __off == 0 && _M_buf_size > 1 )
408 this->setp(_M_buf, _M_buf + _M_buf_size - 1);
414 // [27.8.1.5] Template class basic_ifstream
416 * @brief Controlling input for files.
419 * @tparam _CharT Type of character stream.
420 * @tparam _Traits Traits for character type, defaults to
421 * char_traits<_CharT>.
423 * This class supports reading from named files, using the inherited
424 * functions from std::basic_istream. To control the associated
425 * sequence, an instance of std::basic_filebuf is used, which this page
426 * refers to as @c sb.
428 template<typename _CharT, typename _Traits>
429 class basic_ifstream : public basic_istream<_CharT, _Traits>
433 typedef _CharT char_type;
434 typedef _Traits traits_type;
435 typedef typename traits_type::int_type int_type;
436 typedef typename traits_type::pos_type pos_type;
437 typedef typename traits_type::off_type off_type;
439 // Non-standard types:
440 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
441 typedef basic_istream<char_type, traits_type> __istream_type;
444 __filebuf_type _M_filebuf;
447 // Constructors/Destructors:
449 * @brief Default constructor.
451 * Initializes @c sb using its default constructor, and passes
452 * @c &sb to the base class initializer. Does not open any files
453 * (you haven't given it a filename to open).
455 basic_ifstream() : __istream_type(), _M_filebuf()
456 { this->init(&_M_filebuf); }
459 * @brief Create an input file stream.
460 * @param __s Null terminated string specifying the filename.
461 * @param __mode Open file in specified mode (see std::ios_base).
463 * @c ios_base::in is automatically included in @a __mode.
465 * Tip: When using std::string to hold the filename, you must use
466 * .c_str() before passing it to this constructor.
469 basic_ifstream(const char* __s, ios_base::openmode __mode = ios_base::in)
470 : __istream_type(), _M_filebuf()
472 this->init(&_M_filebuf);
473 this->open(__s, __mode);
476 #if __cplusplus >= 201103L
478 * @brief Create an input file stream.
479 * @param __s std::string specifying the filename.
480 * @param __mode Open file in specified mode (see std::ios_base).
482 * @c ios_base::in is automatically included in @a __mode.
485 basic_ifstream(const std::string& __s,
486 ios_base::openmode __mode = ios_base::in)
487 : __istream_type(), _M_filebuf()
489 this->init(&_M_filebuf);
490 this->open(__s, __mode);
495 * @brief The destructor does nothing.
497 * The file is closed by the filebuf object, not the formatting
505 * @brief Accessing the underlying buffer.
506 * @return The current basic_filebuf buffer.
508 * This hides both signatures of std::basic_ios::rdbuf().
512 { return const_cast<__filebuf_type*>(&_M_filebuf); }
515 * @brief Wrapper to test for an open file.
516 * @return @c rdbuf()->is_open()
520 { return _M_filebuf.is_open(); }
522 // _GLIBCXX_RESOLVE_LIB_DEFECTS
523 // 365. Lack of const-qualification in clause 27
526 { return _M_filebuf.is_open(); }
529 * @brief Opens an external file.
530 * @param __s The name of the file.
531 * @param __mode The open mode flags.
533 * Calls @c std::basic_filebuf::open(s,__mode|in). If that function
534 * fails, @c failbit is set in the stream's error state.
536 * Tip: When using std::string to hold the filename, you must use
537 * .c_str() before passing it to this constructor.
540 open(const char* __s, ios_base::openmode __mode = ios_base::in)
542 if (!_M_filebuf.open(__s, __mode | ios_base::in))
543 this->setstate(ios_base::failbit);
545 // _GLIBCXX_RESOLVE_LIB_DEFECTS
546 // 409. Closing an fstream should clear error state
550 #if __cplusplus >= 201103L
552 * @brief Opens an external file.
553 * @param __s The name of the file.
554 * @param __mode The open mode flags.
556 * Calls @c std::basic_filebuf::open(__s,__mode|in). If that function
557 * fails, @c failbit is set in the stream's error state.
560 open(const std::string& __s, ios_base::openmode __mode = ios_base::in)
562 if (!_M_filebuf.open(__s, __mode | ios_base::in))
563 this->setstate(ios_base::failbit);
565 // _GLIBCXX_RESOLVE_LIB_DEFECTS
566 // 409. Closing an fstream should clear error state
572 * @brief Close the file.
574 * Calls @c std::basic_filebuf::close(). If that function
575 * fails, @c failbit is set in the stream's error state.
580 if (!_M_filebuf.close())
581 this->setstate(ios_base::failbit);
586 // [27.8.1.8] Template class basic_ofstream
588 * @brief Controlling output for files.
591 * @tparam _CharT Type of character stream.
592 * @tparam _Traits Traits for character type, defaults to
593 * char_traits<_CharT>.
595 * This class supports reading from named files, using the inherited
596 * functions from std::basic_ostream. To control the associated
597 * sequence, an instance of std::basic_filebuf is used, which this page
598 * refers to as @c sb.
600 template<typename _CharT, typename _Traits>
601 class basic_ofstream : public basic_ostream<_CharT,_Traits>
605 typedef _CharT char_type;
606 typedef _Traits traits_type;
607 typedef typename traits_type::int_type int_type;
608 typedef typename traits_type::pos_type pos_type;
609 typedef typename traits_type::off_type off_type;
611 // Non-standard types:
612 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
613 typedef basic_ostream<char_type, traits_type> __ostream_type;
616 __filebuf_type _M_filebuf;
621 * @brief Default constructor.
623 * Initializes @c sb using its default constructor, and passes
624 * @c &sb to the base class initializer. Does not open any files
625 * (you haven't given it a filename to open).
627 basic_ofstream(): __ostream_type(), _M_filebuf()
628 { this->init(&_M_filebuf); }
631 * @brief Create an output file stream.
632 * @param __s Null terminated string specifying the filename.
633 * @param __mode Open file in specified mode (see std::ios_base).
635 * @c ios_base::out | @c ios_base::trunc is automatically included in
638 * Tip: When using std::string to hold the filename, you must use
639 * .c_str() before passing it to this constructor.
642 basic_ofstream(const char* __s,
643 ios_base::openmode __mode = ios_base::out|ios_base::trunc)
644 : __ostream_type(), _M_filebuf()
646 this->init(&_M_filebuf);
647 this->open(__s, __mode);
650 #if __cplusplus >= 201103L
652 * @brief Create an output file stream.
653 * @param __s std::string specifying the filename.
654 * @param __mode Open file in specified mode (see std::ios_base).
656 * @c ios_base::out | @c ios_base::trunc is automatically included in
660 basic_ofstream(const std::string& __s,
661 ios_base::openmode __mode = ios_base::out|ios_base::trunc)
662 : __ostream_type(), _M_filebuf()
664 this->init(&_M_filebuf);
665 this->open(__s, __mode);
670 * @brief The destructor does nothing.
672 * The file is closed by the filebuf object, not the formatting
680 * @brief Accessing the underlying buffer.
681 * @return The current basic_filebuf buffer.
683 * This hides both signatures of std::basic_ios::rdbuf().
687 { return const_cast<__filebuf_type*>(&_M_filebuf); }
690 * @brief Wrapper to test for an open file.
691 * @return @c rdbuf()->is_open()
695 { return _M_filebuf.is_open(); }
697 // _GLIBCXX_RESOLVE_LIB_DEFECTS
698 // 365. Lack of const-qualification in clause 27
701 { return _M_filebuf.is_open(); }
704 * @brief Opens an external file.
705 * @param __s The name of the file.
706 * @param __mode The open mode flags.
708 * Calls @c std::basic_filebuf::open(__s,__mode|out|trunc). If that
709 * function fails, @c failbit is set in the stream's error state.
711 * Tip: When using std::string to hold the filename, you must use
712 * .c_str() before passing it to this constructor.
715 open(const char* __s,
716 ios_base::openmode __mode = ios_base::out | ios_base::trunc)
718 if (!_M_filebuf.open(__s, __mode | ios_base::out))
719 this->setstate(ios_base::failbit);
721 // _GLIBCXX_RESOLVE_LIB_DEFECTS
722 // 409. Closing an fstream should clear error state
726 #if __cplusplus >= 201103L
728 * @brief Opens an external file.
729 * @param __s The name of the file.
730 * @param __mode The open mode flags.
732 * Calls @c std::basic_filebuf::open(s,mode|out|trunc). If that
733 * function fails, @c failbit is set in the stream's error state.
736 open(const std::string& __s,
737 ios_base::openmode __mode = ios_base::out | ios_base::trunc)
739 if (!_M_filebuf.open(__s, __mode | ios_base::out))
740 this->setstate(ios_base::failbit);
742 // _GLIBCXX_RESOLVE_LIB_DEFECTS
743 // 409. Closing an fstream should clear error state
749 * @brief Close the file.
751 * Calls @c std::basic_filebuf::close(). If that function
752 * fails, @c failbit is set in the stream's error state.
757 if (!_M_filebuf.close())
758 this->setstate(ios_base::failbit);
763 // [27.8.1.11] Template class basic_fstream
765 * @brief Controlling input and output for files.
768 * @tparam _CharT Type of character stream.
769 * @tparam _Traits Traits for character type, defaults to
770 * char_traits<_CharT>.
772 * This class supports reading from and writing to named files, using
773 * the inherited functions from std::basic_iostream. To control the
774 * associated sequence, an instance of std::basic_filebuf is used, which
775 * this page refers to as @c sb.
777 template<typename _CharT, typename _Traits>
778 class basic_fstream : public basic_iostream<_CharT, _Traits>
782 typedef _CharT char_type;
783 typedef _Traits traits_type;
784 typedef typename traits_type::int_type int_type;
785 typedef typename traits_type::pos_type pos_type;
786 typedef typename traits_type::off_type off_type;
788 // Non-standard types:
789 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
790 typedef basic_ios<char_type, traits_type> __ios_type;
791 typedef basic_iostream<char_type, traits_type> __iostream_type;
794 __filebuf_type _M_filebuf;
797 // Constructors/destructor:
799 * @brief Default constructor.
801 * Initializes @c sb using its default constructor, and passes
802 * @c &sb to the base class initializer. Does not open any files
803 * (you haven't given it a filename to open).
806 : __iostream_type(), _M_filebuf()
807 { this->init(&_M_filebuf); }
810 * @brief Create an input/output file stream.
811 * @param __s Null terminated string specifying the filename.
812 * @param __mode Open file in specified mode (see std::ios_base).
814 * Tip: When using std::string to hold the filename, you must use
815 * .c_str() before passing it to this constructor.
818 basic_fstream(const char* __s,
819 ios_base::openmode __mode = ios_base::in | ios_base::out)
820 : __iostream_type(0), _M_filebuf()
822 this->init(&_M_filebuf);
823 this->open(__s, __mode);
826 #if __cplusplus >= 201103L
828 * @brief Create an input/output file stream.
829 * @param __s Null terminated string specifying the filename.
830 * @param __mode Open file in specified mode (see std::ios_base).
833 basic_fstream(const std::string& __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);
843 * @brief The destructor does nothing.
845 * The file is closed by the filebuf object, not the formatting
853 * @brief Accessing the underlying buffer.
854 * @return The current basic_filebuf buffer.
856 * This hides both signatures of std::basic_ios::rdbuf().
860 { return const_cast<__filebuf_type*>(&_M_filebuf); }
863 * @brief Wrapper to test for an open file.
864 * @return @c rdbuf()->is_open()
868 { return _M_filebuf.is_open(); }
870 // _GLIBCXX_RESOLVE_LIB_DEFECTS
871 // 365. Lack of const-qualification in clause 27
874 { return _M_filebuf.is_open(); }
877 * @brief Opens an external file.
878 * @param __s The name of the file.
879 * @param __mode The open mode flags.
881 * Calls @c std::basic_filebuf::open(__s,__mode). If that
882 * function fails, @c failbit is set in the stream's error state.
884 * Tip: When using std::string to hold the filename, you must use
885 * .c_str() before passing it to this constructor.
888 open(const char* __s,
889 ios_base::openmode __mode = ios_base::in | ios_base::out)
891 if (!_M_filebuf.open(__s, __mode))
892 this->setstate(ios_base::failbit);
894 // _GLIBCXX_RESOLVE_LIB_DEFECTS
895 // 409. Closing an fstream should clear error state
899 #if __cplusplus >= 201103L
901 * @brief Opens an external file.
902 * @param __s The name of the file.
903 * @param __mode The open mode flags.
905 * Calls @c std::basic_filebuf::open(__s,__mode). If that
906 * function fails, @c failbit is set in the stream's error state.
909 open(const std::string& __s,
910 ios_base::openmode __mode = ios_base::in | ios_base::out)
912 if (!_M_filebuf.open(__s, __mode))
913 this->setstate(ios_base::failbit);
915 // _GLIBCXX_RESOLVE_LIB_DEFECTS
916 // 409. Closing an fstream should clear error state
922 * @brief Close the file.
924 * Calls @c std::basic_filebuf::close(). If that function
925 * fails, @c failbit is set in the stream's error state.
930 if (!_M_filebuf.close())
931 this->setstate(ios_base::failbit);
935 _GLIBCXX_END_NAMESPACE_VERSION
938 #include <bits/fstream.tcc>
940 #endif /* _GLIBCXX_FSTREAM */