// This is part of the iostream library, providing input/output for C++.
// Copyright (C) 1991, 1992 Per Bothner.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free
// Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
// An fstream can be in at most one of put mode, get mode, or putback mode.
// Putback mode is a variant of get mode.
// In a filebuf, there is only one current position, instead of two
// separate get and put pointers. In get mode, the current posistion
// is that of gptr(); in put mode that of pptr().
// The position in the buffer that corresponds to the position
// in external file system is file_ptr().
// This is normally egptr(), except in putback mode, when it is _save_egptr.
// If the field _fb._offset is >= 0, it gives the offset in
// the file as a whole corresponding to eGptr(). (???)
// If a filebuf is in put mode, pbase() is non-NULL and equal to base().
// Also, epptr() == ebuf().
// Also, eback() == gptr() && gptr() == egptr().
// The un-flushed character are those between pbase() and pptr().
// If a filebuf is in get or putback mode, eback() != egptr().
// In get mode, the unread characters are between gptr() and egptr().
// The OS file position corresponds to that of egptr().
// Putback mode is used to remember "excess" characters that have
// been sputbackc'd in a separate putback buffer.
// In putback mode, the get buffer points to the special putback buffer.
// The unread characters are the characters between gptr() and egptr()
// in the putback buffer, as well as the area between save_gptr()
// and save_egptr(), which point into the original reserve buffer.
// (The pointers save_gptr() and save_egptr() are the values
// of gptr() and egptr() at the time putback mode was entered.)
// The OS position corresponds to that of save_egptr().
// During line buffered output, pbase()==base() && epptr()==base().
// However, ptr() may be anywhere between base() and ebuf().
// This forces a call to filebuf::overflow(int C) on every put.
// If there is more space in the buffer, and C is not a '\n',
// then C is inserted, and pptr() incremented.
// If a filebuf is unbuffered(), the _shortbuf[1] is used as the buffer.
#define CLOSED_FILEBUF_FLAGS \
(_S_IS_FILEBUF+_S_NO_READS+_S_NO_WRITES+_S_TIED_PUT_GET)
filebuf::filebuf() : backupbuf(CLOSED_FILEBUF_FLAGS)
filebuf::filebuf(int fd) : backupbuf(CLOSED_FILEBUF_FLAGS)
filebuf::filebuf(int fd, char* p, int len) : backupbuf(CLOSED_FILEBUF_FLAGS)
if (!(xflags() & _S_DELETE_DONT_CLOSE))
filebuf* filebuf::open(const char *filename, ios::openmode mode, int prot)
if ((mode & (ios::in|ios::out)) == (ios::in|ios::out)) {
else if (mode & ios::out)
posix_mode = O_WRONLY, read_write = _S_NO_READS;
else if (mode & (int)ios::in)
posix_mode = O_RDONLY, read_write = _S_NO_WRITES;
posix_mode = 0, read_write = _S_NO_READS+_S_NO_WRITES;
if ((mode & (int)ios::trunc) || mode == (int)ios::out)
posix_mode |= O_APPEND, read_write |= _S_IS_APPENDING;
if (!(mode & (int)ios::nocreate) && mode != ios::in)
if (mode & (int)ios::noreplace)
int fd = ::open(filename, posix_mode, prot);
xsetflags(read_write, _S_NO_READS+_S_NO_WRITES+_S_IS_APPENDING);
if (mode & (ios::ate|ios::app)) {
if (seekoff(0, ios::end) == EOF)
filebuf* filebuf::open(const char *filename, const char *mode)
read_write = _S_NO_WRITES;
oflags = O_CREAT|O_TRUNC;
read_write = _S_NO_READS;
oflags = O_CREAT|O_APPEND;
read_write = _S_NO_READS|_S_IS_APPENDING;
if (mode[0] == '+' || (mode[0] == 'b' && mode[1] == '+')) {
read_write &= _S_IS_APPENDING;
int fdesc = ::open(filename, omode|oflags, oprot);
xsetflags(read_write, _S_NO_READS+_S_NO_WRITES+_S_IS_APPENDING);
if (read_write & _S_IS_APPENDING)
if (seekoff(0, ios::end) == EOF)
filebuf* filebuf::attach(int fd)
xsetflags(0, _S_NO_READS+_S_NO_WRITES);
streambuf* filebuf::setbuf(char* p, int len)
if (streambuf::setbuf(p, len) == NULL)
setg(_base, _base, _base);
int filebuf::overflow(int c)
if (xflags() & _S_NO_WRITES) // SET ERROR
// Allocate a buffer if needed.
if (xflags() & _S_LINE_BUF+_S_UNBUFFERED) setp(_base, _base);
setg(_base, _base, _base);
_flags |= _S_CURRENTLY_PUTTING;
// If currently reading, switch to writing.
else if ((_flags & _S_CURRENTLY_PUTTING) == 0) {
if (xflags() & _S_LINE_BUF+_S_UNBUFFERED) setp(gptr(), gptr());
else setp(gptr(), ebuf());
setg(egptr(), egptr(), egptr());
_flags |= _S_CURRENTLY_PUTTING;
if (pptr() == ebuf() ) // Buffer is really full
if (unbuffered() || (linebuffered() && c == '\n'))
/* SysV does not make this test; take it out for compatibility */
if (xflags() & _S_NO_READS)
return *(unsigned char*)gptr();
// FIXME This can/should be moved to __streambuf ??
if ((xflags() & _S_LINE_BUF) || unbuffered()) {
// Flush all line buffered files before reading.
streambuf::flush_all_linebuffered();
_G_ssize_t count = sys_read(base(), ebuf() - base());
xsetflags(_S_ERR_SEEN), count = 0;
setg(base(), base(), base() + count);
return *(unsigned char*)gptr();
int filebuf::do_write(const char *data, int to_do)
if (xflags() & _S_IS_APPENDING) {
// On a system without a proper O_APPEND implementation,
// you would need to sys_seek(0, ios::end) here, but is
// is not needed nor desirable for Unix- or Posix-like systems.
// Instead, just indicate that offset (before and after) is
else if (egptr() != pbase()) {
long new_pos = sys_seek(pbase()-egptr(), ios::cur);
_G_ssize_t count = sys_write(data, to_do);
_cur_column = __adjust_column(_cur_column - 1, data, to_do) + 1;
setg(base(), base(), base());
if (xflags() & _S_LINE_BUF+_S_UNBUFFERED) setp(base(), base());
else setp(base(), ebuf());
return count != to_do ? EOF : 0;
// char* ptr = cur_ptr();
if (do_flush()) return EOF;
streampos delta = gptr() - egptr();
delta -= eGptr() - Gbase();
_G_fpos_t new_pos = sys_seek(delta, ios::cur);
setg(eback(), gptr(), gptr());
// FIXME: Cleanup - can this be shared?
// setg(base(), ptr, ptr);
streampos filebuf::seekoff(streamoff offset, _seek_dir dir, int mode)
streampos result, new_offset, delta;
if (mode == 0) // Don't move any pointers.
dir = ios::cur, offset = 0;
// Flush unwritten characters.
// (This may do an unneeded write if we seek within the buffer.
// But to be able to switch to reading, we would need to set
// egptr to ptr. That can't be done in the current design,
// which assumes file_ptr() is eGptr. Anyway, since we probably
// end up flushing when we close(), it doesn't make much difference.)
if (pptr() > pbase() || put_mode())
if (switch_to_get_mode()) return EOF;
setg(base(), base(), base());
_fb._offset = sys_seek(0, ios::cur);
// Make offset absolute, assuming current pointer is file_ptr().
offset -= _egptr - _gptr;
offset -= _other_egptr - _other_gbase;
if (sys_stat(&st) == 0 && S_ISREG(st.st_mode)) {
// At this point, dir==ios::beg.
// If destination is within current buffer, optimize:
if (_fb._offset >= 0 && _eback != NULL) {
// Offset relative to start of main get area.
_G_fpos_t rel_offset = offset - _fb._offset
switch_to_main_get_area();
if (rel_offset <= _egptr - _eback) {
setg(base(), base() + rel_offset, egptr());
// If we have streammarkers, seek forward by reading ahead.
int to_skip = rel_offset - (_gptr - _eback);
if (ignore(to_skip) != to_skip)
if (rel_offset < 0 && rel_offset >= Bbase() - Bptr()) {
gbump(_egptr + rel_offset - gptr());
// Try to seek to a block boundary, to improve kernel page management.
new_offset = offset & ~(ebuf() - base() - 1);
delta = offset - new_offset;
if (delta > ebuf() - base()) {
result = sys_seek(new_offset, ios::beg);
count = sys_read(base(), ebuf()-base());
// We weren't allowed to read, but try to seek the remainder.
offset = count == EOF ? delta : delta-count;
setg(base(), base()+delta, base()+count);
_fb._offset = result + count;
xflags(xflags() & ~ _S_EOF_SEEN);
result = sys_seek(offset, dir);
xflags(xflags() & ~_S_EOF_SEEN);
setg(base(), base(), base());
filebuf* filebuf::close()
// This flushes as well as switching mode.
if (pptr() > pbase() || put_mode())
if (switch_to_get_mode()) return NULL;
int status = sys_close();
_flags = _IO_MAGIC|CLOSED_FILEBUF_FLAGS;
return status < 0 ? NULL : this;
_G_ssize_t filebuf::sys_read(char* buf, size_t size)
_G_ssize_t count = ::read(_fb._fileno, buf, size);
if (count != -1 || errno != EINTR)
_G_fpos_t filebuf::sys_seek(_G_fpos_t offset, _seek_dir dir)
return ::lseek(fd(), offset, (int)dir);
_G_ssize_t filebuf::sys_write(const void *buf, long n)
_G_ssize_t count = ::write(fd(), buf, to_do);
buf = (void*)((char*)buf + count);
int filebuf::sys_stat(void* st)
return ::_fstat(fd(), (struct stat*)st);
int filebuf::xsputn(const char *s, int n)
// This is an optimized implementation.
// If the amount to be written straddles a block boundary
// (or the filebuf is unbuffered), use sys_write directly.
// First figure out how much space is available in the buffer.
int count = _epptr - _pptr; // Space available.
if (linebuffered() && (_flags & _S_CURRENTLY_PUTTING)) {
for (register const char *p = s + n; p > s; ) {
memcpy(pptr(), s, count);
register char *p = pptr();;
for (register int i = count; --i >= 0; ) *p++ = *s++;
if (to_do + must_flush > 0) {
// Next flush the (full) buffer.
if (__overflow(this, EOF) == EOF)
// Try to maintain alignment: write a whole number of blocks.
// dont_write is what gets left over.
int block_size = _ebuf - _base;
int dont_write = block_size >= 128 ? to_do % block_size : 0;
_G_ssize_t count = to_do - dont_write;
if (do_write(s, count) == EOF)
// Now write out the remainder. Normally, this will fit in the
// buffer, but it's somewhat messier for line-buffered files,
// so we let streambuf::sputn handle the general case.
to_do -= streambuf::sputn(s+count, dont_write);
int filebuf::xsgetn(char *s, int n)
// FIXME: OPTIMIZE THIS (specifically, when unbuffered()).
return streambuf::xsgetn(s, n);
// Non-ANSI AT&T-ism: Default open protection.
const int filebuf::openprot = 0644;