1 // File based streams -*- C++ -*-
3 // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4 // 2006, 2007, 2008, 2009
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 2, 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 // You should have received a copy of the GNU General Public License
19 // along with this library; see the file COPYING. If not, write to
20 // the Free Software Foundation, 51 Franklin Street, Fifth Floor,
21 // Boston, MA 02110-1301, USA.
23 // As a special exception, you may use this file as part of a free software
24 // library without restriction. Specifically, if other files instantiate
25 // templates or use macros or inline functions from this file, or you compile
26 // this file and link it with other files to produce an executable, this
27 // file does not by itself cause the resulting executable to be covered by
28 // the GNU General Public License. This exception does not however
29 // invalidate any other reasons why the executable file might be covered by
30 // the GNU General Public License.
33 * This is a Standard C++ Library header.
37 // ISO C++ 14882: 27.8 File-based streams
40 #ifndef _GLIBCXX_FSTREAM
41 #define _GLIBCXX_FSTREAM 1
43 #pragma GCC system_header
47 #include <bits/codecvt.h>
48 #include <cstdio> // For BUFSIZ
49 #include <bits/basic_file.h> // For __basic_file, __c_lock
51 _GLIBCXX_BEGIN_NAMESPACE(std)
53 // [27.8.1.1] template class basic_filebuf
55 * @brief The actual work of input and output (for files).
58 * This class associates both its input and output sequence with an
59 * external disk file, and maintains a joint file position for both
60 * sequences. Many of its semantics are described in terms of similar
61 * behavior in the Standard C Library's @c FILE streams.
63 // Requirements on traits_type, specific to this class:
64 // traits_type::pos_type must be fpos<traits_type::state_type>
65 // traits_type::off_type must be streamoff
66 // traits_type::state_type must be Assignable and DefaultConstructible,
67 // and traits_type::state_type() must be the initial state for codecvt.
68 template<typename _CharT, typename _Traits>
69 class basic_filebuf : public basic_streambuf<_CharT, _Traits>
73 typedef _CharT char_type;
74 typedef _Traits traits_type;
75 typedef typename traits_type::int_type int_type;
76 typedef typename traits_type::pos_type pos_type;
77 typedef typename traits_type::off_type off_type;
79 typedef basic_streambuf<char_type, traits_type> __streambuf_type;
80 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
81 typedef __basic_file<char> __file_type;
82 typedef typename traits_type::state_type __state_type;
83 typedef codecvt<char_type, char, __state_type> __codecvt_type;
85 friend class ios_base; // For sync_with_stdio.
89 // MT lock inherited from libio or other low-level io library.
95 /// Place to stash in || out || in | out settings for current filebuf.
96 ios_base::openmode _M_mode;
98 // Beginning state type for codecvt.
99 __state_type _M_state_beg;
101 // During output, the state that corresponds to pptr(),
102 // during input, the state that corresponds to egptr() and
104 __state_type _M_state_cur;
106 // Not used for output. During input, the state that corresponds
107 // to eback() and _M_ext_buf.
108 __state_type _M_state_last;
110 /// Pointer to the beginning of internal buffer.
114 * Actual size of internal buffer. This number is equal to the size
115 * of the put area + 1 position, reserved for the overflow char of
120 // Set iff _M_buf is allocated memory from _M_allocate_internal_buffer.
121 bool _M_buf_allocated;
124 * _M_reading == false && _M_writing == false for 'uncommitted' mode;
125 * _M_reading == true for 'read' mode;
126 * _M_writing == true for 'write' mode;
128 * NB: _M_reading == true && _M_writing == true is unused.
135 * Necessary bits for putback buffer management.
137 * @note pbacks of over one character are not currently supported.
140 char_type* _M_pback_cur_save;
141 char_type* _M_pback_end_save;
145 // Cached codecvt facet.
146 const __codecvt_type* _M_codecvt;
149 * Buffer for external characters. Used for input when
150 * codecvt::always_noconv() == false. When valid, this corresponds
156 * Size of buffer held by _M_ext_buf.
158 streamsize _M_ext_buf_size;
161 * Pointers into the buffer held by _M_ext_buf that delimit a
162 * subsequence of bytes that have been read but not yet converted.
163 * When valid, _M_ext_next corresponds to egptr().
165 const char* _M_ext_next;
169 * Initializes pback buffers, and moves normal buffers to safety.
171 * _M_in_cur has already been moved back
178 _M_pback_cur_save = this->gptr();
179 _M_pback_end_save = this->egptr();
180 this->setg(&_M_pback, &_M_pback, &_M_pback + 1);
181 _M_pback_init = true;
186 * Deactivates pback buffer contents, and restores normal buffer.
188 * The pback buffer has only moved forward.
191 _M_destroy_pback() throw()
195 // Length _M_in_cur moved in the pback buffer.
196 _M_pback_cur_save += this->gptr() != this->eback();
197 this->setg(_M_buf, _M_pback_cur_save, _M_pback_end_save);
198 _M_pback_init = false;
203 // Constructors/destructor:
205 * @brief Does not open any files.
207 * The default constructor initializes the parent class using its
213 * @brief The destructor closes the file first.
221 * @brief Returns true if the external file is open.
224 is_open() const throw()
225 { return _M_file.is_open(); }
228 * @brief Opens an external file.
229 * @param s The name of the file.
230 * @param mode The open mode flags.
231 * @return @c this on success, NULL on failure
233 * If a file is already open, this function immediately fails.
234 * Otherwise it tries to open the file named @a s using the flags
237 * Table 92, adapted here, gives the relation between openmode
238 * combinations and the equivalent fopen() flags.
239 * (NB: lines app, in|out|app, in|app, binary|app, binary|in|out|app,
240 * and binary|in|app per DR 596)
241 * +---------------------------------------------------------+
242 * | ios_base Flag combination stdio equivalent |
243 * |binary in out trunc app |
244 * +---------------------------------------------------------+
254 * +---------------------------------------------------------+
264 * +---------------------------------------------------------+
267 open(const char* __s, ios_base::openmode __mode);
270 * @brief Closes the currently associated file.
271 * @return @c this on success, NULL on failure
273 * If no file is currently open, this function immediately fails.
275 * If a "put buffer area" exists, @c overflow(eof) is called to flush
276 * all the characters. The file is then closed.
278 * If any operations fail, this function also fails.
285 _M_allocate_internal_buffer();
288 _M_destroy_internal_buffer() throw();
290 // [27.8.1.4] overridden virtual functions
294 // Stroustrup, 1998, p. 628
295 // underflow() and uflow() functions are called to get the next
296 // character from the real input source when the buffer is empty.
297 // Buffered input uses underflow()
303 pbackfail(int_type __c = _Traits::eof());
305 // Stroustrup, 1998, p 648
306 // The overflow() function is called to transfer characters to the
307 // real output destination when the buffer is full. A call to
308 // overflow(c) outputs the contents of the buffer plus the
311 // Consume some sequence of the characters in the pending sequence.
313 overflow(int_type __c = _Traits::eof());
315 // Convert internal byte sequence to external, char-based
316 // sequence via codecvt.
318 _M_convert_to_external(char_type*, streamsize);
321 * @brief Manipulates the buffer.
322 * @param s Pointer to a buffer area.
323 * @param n Size of @a s.
326 * If no file has been opened, and both @a s and @a n are zero, then
327 * the stream becomes unbuffered. Otherwise, @c s is used as a
329 * http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt11ch25s02.html
332 virtual __streambuf_type*
333 setbuf(char_type* __s, streamsize __n);
336 seekoff(off_type __off, ios_base::seekdir __way,
337 ios_base::openmode __mode = ios_base::in | ios_base::out);
340 seekpos(pos_type __pos,
341 ios_base::openmode __mode = ios_base::in | ios_base::out);
343 // Common code for seekoff and seekpos
345 _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state);
351 imbue(const locale& __loc);
354 xsgetn(char_type* __s, streamsize __n);
357 xsputn(const char_type* __s, streamsize __n);
359 // Flushes output buffer, then writes unshift sequence.
361 _M_terminate_output();
364 * This function sets the pointers of the internal buffer, both get
365 * and put areas. Typically:
367 * __off == egptr() - eback() upon underflow/uflow ('read' mode);
368 * __off == 0 upon overflow ('write' mode);
369 * __off == -1 upon open, setbuf, seekoff/pos ('uncommitted' mode).
371 * NB: epptr() - pbase() == _M_buf_size - 1, since _M_buf_size
372 * reflects the actual allocated memory and the last cell is reserved
373 * for the overflow char of a full put area.
376 _M_set_buffer(streamsize __off)
378 const bool __testin = _M_mode & ios_base::in;
379 const bool __testout = _M_mode & ios_base::out;
381 if (__testin && __off > 0)
382 this->setg(_M_buf, _M_buf, _M_buf + __off);
384 this->setg(_M_buf, _M_buf, _M_buf);
386 if (__testout && __off == 0 && _M_buf_size > 1 )
387 this->setp(_M_buf, _M_buf + _M_buf_size - 1);
389 this->setp(NULL, NULL);
393 // [27.8.1.5] Template class basic_ifstream
395 * @brief Controlling input for files.
398 * This class supports reading from named files, using the inherited
399 * functions from std::basic_istream. To control the associated
400 * sequence, an instance of std::basic_filebuf is used, which this page
401 * refers to as @c sb.
403 template<typename _CharT, typename _Traits>
404 class basic_ifstream : public basic_istream<_CharT, _Traits>
408 typedef _CharT char_type;
409 typedef _Traits traits_type;
410 typedef typename traits_type::int_type int_type;
411 typedef typename traits_type::pos_type pos_type;
412 typedef typename traits_type::off_type off_type;
414 // Non-standard types:
415 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
416 typedef basic_istream<char_type, traits_type> __istream_type;
419 __filebuf_type _M_filebuf;
422 // Constructors/Destructors:
424 * @brief Default constructor.
426 * Initializes @c sb using its default constructor, and passes
427 * @c &sb to the base class initializer. Does not open any files
428 * (you haven't given it a filename to open).
430 basic_ifstream() : __istream_type(), _M_filebuf()
431 { this->init(&_M_filebuf); }
434 * @brief Create an input file stream.
435 * @param s Null terminated string specifying the filename.
436 * @param mode Open file in specified mode (see std::ios_base).
438 * @c ios_base::in is automatically included in @a mode.
440 * Tip: When using std::string to hold the filename, you must use
441 * .c_str() before passing it to this constructor.
444 basic_ifstream(const char* __s, ios_base::openmode __mode = ios_base::in)
445 : __istream_type(), _M_filebuf()
447 this->init(&_M_filebuf);
448 this->open(__s, __mode);
452 * @brief The destructor does nothing.
454 * The file is closed by the filebuf object, not the formatting
462 * @brief Accessing the underlying buffer.
463 * @return The current basic_filebuf buffer.
465 * This hides both signatures of std::basic_ios::rdbuf().
469 { return const_cast<__filebuf_type*>(&_M_filebuf); }
472 * @brief Wrapper to test for an open file.
473 * @return @c rdbuf()->is_open()
477 { return _M_filebuf.is_open(); }
479 // _GLIBCXX_RESOLVE_LIB_DEFECTS
480 // 365. Lack of const-qualification in clause 27
483 { return _M_filebuf.is_open(); }
486 * @brief Opens an external file.
487 * @param s The name of the file.
488 * @param mode The open mode flags.
490 * Calls @c std::basic_filebuf::open(s,mode|in). If that function
491 * fails, @c failbit is set in the stream's error state.
493 * Tip: When using std::string to hold the filename, you must use
494 * .c_str() before passing it to this constructor.
497 open(const char* __s, ios_base::openmode __mode = ios_base::in)
499 if (!_M_filebuf.open(__s, __mode | ios_base::in))
500 this->setstate(ios_base::failbit);
502 // _GLIBCXX_RESOLVE_LIB_DEFECTS
503 // 409. Closing an fstream should clear error state
508 * @brief Close the file.
510 * Calls @c std::basic_filebuf::close(). If that function
511 * fails, @c failbit is set in the stream's error state.
516 if (!_M_filebuf.close())
517 this->setstate(ios_base::failbit);
522 // [27.8.1.8] Template class basic_ofstream
524 * @brief Controlling output for files.
527 * This class supports reading from named files, using the inherited
528 * functions from std::basic_ostream. To control the associated
529 * sequence, an instance of std::basic_filebuf is used, which this page
530 * refers to as @c sb.
532 template<typename _CharT, typename _Traits>
533 class basic_ofstream : public basic_ostream<_CharT,_Traits>
537 typedef _CharT char_type;
538 typedef _Traits traits_type;
539 typedef typename traits_type::int_type int_type;
540 typedef typename traits_type::pos_type pos_type;
541 typedef typename traits_type::off_type off_type;
543 // Non-standard types:
544 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
545 typedef basic_ostream<char_type, traits_type> __ostream_type;
548 __filebuf_type _M_filebuf;
553 * @brief Default constructor.
555 * Initializes @c sb using its default constructor, and passes
556 * @c &sb to the base class initializer. Does not open any files
557 * (you haven't given it a filename to open).
559 basic_ofstream(): __ostream_type(), _M_filebuf()
560 { this->init(&_M_filebuf); }
563 * @brief Create an output file stream.
564 * @param s Null terminated string specifying the filename.
565 * @param mode Open file in specified mode (see std::ios_base).
567 * @c ios_base::out|ios_base::trunc is automatically included in
570 * Tip: When using std::string to hold the filename, you must use
571 * .c_str() before passing it to this constructor.
574 basic_ofstream(const char* __s,
575 ios_base::openmode __mode = ios_base::out|ios_base::trunc)
576 : __ostream_type(), _M_filebuf()
578 this->init(&_M_filebuf);
579 this->open(__s, __mode);
583 * @brief The destructor does nothing.
585 * The file is closed by the filebuf object, not the formatting
593 * @brief Accessing the underlying buffer.
594 * @return The current basic_filebuf buffer.
596 * This hides both signatures of std::basic_ios::rdbuf().
600 { return const_cast<__filebuf_type*>(&_M_filebuf); }
603 * @brief Wrapper to test for an open file.
604 * @return @c rdbuf()->is_open()
608 { return _M_filebuf.is_open(); }
610 // _GLIBCXX_RESOLVE_LIB_DEFECTS
611 // 365. Lack of const-qualification in clause 27
614 { return _M_filebuf.is_open(); }
617 * @brief Opens an external file.
618 * @param s The name of the file.
619 * @param mode The open mode flags.
621 * Calls @c std::basic_filebuf::open(s,mode|out|trunc). If that
622 * function fails, @c failbit is set in the stream's error state.
624 * Tip: When using std::string to hold the filename, you must use
625 * .c_str() before passing it to this constructor.
628 open(const char* __s,
629 ios_base::openmode __mode = ios_base::out | ios_base::trunc)
631 if (!_M_filebuf.open(__s, __mode | ios_base::out))
632 this->setstate(ios_base::failbit);
634 // _GLIBCXX_RESOLVE_LIB_DEFECTS
635 // 409. Closing an fstream should clear error state
640 * @brief Close the file.
642 * Calls @c std::basic_filebuf::close(). If that function
643 * fails, @c failbit is set in the stream's error state.
648 if (!_M_filebuf.close())
649 this->setstate(ios_base::failbit);
654 // [27.8.1.11] Template class basic_fstream
656 * @brief Controlling input and output for files.
659 * This class supports reading from and writing to named files, using
660 * the inherited functions from std::basic_iostream. To control the
661 * associated sequence, an instance of std::basic_filebuf is used, which
662 * this page refers to as @c sb.
664 template<typename _CharT, typename _Traits>
665 class basic_fstream : public basic_iostream<_CharT, _Traits>
669 typedef _CharT char_type;
670 typedef _Traits traits_type;
671 typedef typename traits_type::int_type int_type;
672 typedef typename traits_type::pos_type pos_type;
673 typedef typename traits_type::off_type off_type;
675 // Non-standard types:
676 typedef basic_filebuf<char_type, traits_type> __filebuf_type;
677 typedef basic_ios<char_type, traits_type> __ios_type;
678 typedef basic_iostream<char_type, traits_type> __iostream_type;
681 __filebuf_type _M_filebuf;
684 // Constructors/destructor:
686 * @brief Default constructor.
688 * Initializes @c sb using its default constructor, and passes
689 * @c &sb to the base class initializer. Does not open any files
690 * (you haven't given it a filename to open).
693 : __iostream_type(), _M_filebuf()
694 { this->init(&_M_filebuf); }
697 * @brief Create an input/output file stream.
698 * @param s Null terminated string specifying the filename.
699 * @param mode Open file in specified mode (see std::ios_base).
701 * Tip: When using std::string to hold the filename, you must use
702 * .c_str() before passing it to this constructor.
705 basic_fstream(const char* __s,
706 ios_base::openmode __mode = ios_base::in | ios_base::out)
707 : __iostream_type(NULL), _M_filebuf()
709 this->init(&_M_filebuf);
710 this->open(__s, __mode);
714 * @brief The destructor does nothing.
716 * The file is closed by the filebuf object, not the formatting
724 * @brief Accessing the underlying buffer.
725 * @return The current basic_filebuf buffer.
727 * This hides both signatures of std::basic_ios::rdbuf().
731 { return const_cast<__filebuf_type*>(&_M_filebuf); }
734 * @brief Wrapper to test for an open file.
735 * @return @c rdbuf()->is_open()
739 { return _M_filebuf.is_open(); }
741 // _GLIBCXX_RESOLVE_LIB_DEFECTS
742 // 365. Lack of const-qualification in clause 27
745 { return _M_filebuf.is_open(); }
748 * @brief Opens an external file.
749 * @param s The name of the file.
750 * @param mode The open mode flags.
752 * Calls @c std::basic_filebuf::open(s,mode). If that
753 * function fails, @c failbit is set in the stream's error state.
755 * Tip: When using std::string to hold the filename, you must use
756 * .c_str() before passing it to this constructor.
759 open(const char* __s,
760 ios_base::openmode __mode = ios_base::in | ios_base::out)
762 if (!_M_filebuf.open(__s, __mode))
763 this->setstate(ios_base::failbit);
765 // _GLIBCXX_RESOLVE_LIB_DEFECTS
766 // 409. Closing an fstream should clear error state
771 * @brief Close the file.
773 * Calls @c std::basic_filebuf::close(). If that function
774 * fails, @c failbit is set in the stream's error state.
779 if (!_M_filebuf.close())
780 this->setstate(ios_base::failbit);
784 _GLIBCXX_END_NAMESPACE
786 #ifndef _GLIBCXX_EXPORT_TEMPLATE
787 # include <bits/fstream.tcc>
790 #endif /* _GLIBCXX_FSTREAM */