3 * Silicon Graphics Computer Systems, Inc.
8 * This material is provided "as is", with absolutely no warranty expressed
9 * or implied. Any use is at your own risk.
11 * Permission to use or copy this software for any purpose is hereby granted
12 * without fee, provided the above notices are retained on all copies.
13 * Permission to modify the code and to distribute modified code is granted,
14 * provided the above notices are retained, and a notice that the code was
15 * modified is included with the above copyright notice.
20 #include "stlport_prefix.h"
22 #if defined (__SUNPPRO_CC) && !defined (_STLP_NO_NEW_C_HEADERS)
24 // For sunpro, it chokes if time.h is included through stat.h
30 # define __int64 long long
33 #if defined (_STLP_USE_UNIX_IO)
35 // open/close/read/write
36 # include <sys/stat.h> // For stat
37 # if !defined (_CRAY) && ! defined (__EMX__)
38 # include <sys/mman.h> // For mmap
41 // on HP-UX 11, this one contradicts with pthread.h on pthread_atfork, unless we unset this
42 # if defined (__hpux) && defined (__GNUC__)
43 # undef _INCLUDE_POSIX1C_SOURCE
50 # include <sys/sysctl.h>
52 #elif defined (_STLP_USE_WIN32_IO)
53 # define WIN32_LEAN_AND_MEAN
57 # include <cfcntl.h> // For _O_RDONLY, etc
58 # include <sys/stat.h> // For _fstat
59 # elif !defined(_STLP_WCE)
60 # include <io.h> // For _get_osfhandle
61 # include <fcntl.h> // For _O_RDONLY, etc
62 # include <sys/stat.h> // For _fstat
64 # define _TEXTBUF_SIZE 0x1000
65 #elif defined (_STLP_USE_UNIX_EMULATION_IO)
66 # if defined( __MSL__ )
72 # include <sys/stat.h>
73 #elif defined (_STLP_USE_STDIO_IO)
75 # if !(defined(__MRC__) || defined(__SC__) || defined(__ISCPP__) )
77 # include <sys/stat.h>
80 # if defined( __MSL__ )
83 # if defined(__ISCPP__)
84 # include <c_locale_is/filestat.h>
86 # if defined(__BEOS__) && defined(__INTEL__)
88 # include <sys/stat.h> // For _fstat
89 # define _S_IREAD S_IREAD
90 # define _S_IWRITE S_IWRITE
91 # define _S_IFREG S_IFREG
94 # error "Configure i/o !"
97 #if defined (_STLP_USE_WIN32_IO)
98 const _STLP_fd INVALID_STLP_FD = INVALID_HANDLE_VALUE;
99 # if !defined (INVALID_SET_FILE_POINTER)
100 # define INVALID_SET_FILE_POINTER 0xffffffff
102 #elif defined (_STLP_USE_UNIX_EMULATION_IO) || defined (_STLP_USE_STDIO_IO) || defined (_STLP_USE_UNIX_IO)
103 const _STLP_fd INVALID_STLP_FD = -1;
105 # error "Configure i/o !"
108 // map permission masks
109 #if defined (_STLP_USE_UNIX_EMULATION_IO) || defined (_STLP_USE_STDIO_IO)
111 # define S_IRUSR _S_IREAD
112 # define S_IWUSR _S_IWRITE
113 # define S_IRGRP _S_IREAD
114 # define S_IWGRP _S_IWRITE
115 # define S_IROTH _S_IREAD
116 # define S_IWOTH _S_IWRITE
119 # define O_RDONLY _O_RDONLY
120 # define O_WRONLY _O_WRONLY
121 # define O_RDWR _O_RDWR
122 # define O_APPEND _O_APPEND
123 # define O_CREAT _O_CREAT
124 # define O_TRUNC _O_TRUNC
125 # define O_TEXT _O_TEXT
126 # define O_BINARY _O_BINARY
131 # if !defined( O_TEXT )
132 # define O_TEXT _O_TEXT
134 # define _S_IFREG S_IFREG
135 # define S_IREAD S_IRUSR
136 # define S_IWRITE S_IWUSR
137 # define S_IEXEC S_IXUSR
138 # define _S_IWRITE S_IWRITE
139 # define _S_IREAD S_IREAD
141 # define _lseek lseek
142 # define _close close
144 # define _write write
149 # define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
152 #include "fstream_impl.h"
154 #ifdef _STLP_LONG_LONG
155 # define ULL(x) ((unsigned _STLP_LONG_LONG)x)
156 #elif defined(__MRC__) || defined(__SC__) //*TY 02/25/2000 - added support for MPW compilers
158 # define ULL(x) (U64SetU(x))
159 #elif defined(__ISCPP__)
162 # error "there should be some long long type on the system!"
165 _STLP_BEGIN_NAMESPACE
166 // Compare with streamoff definition in stl/char_traits.h!
168 #ifdef _STLP_USE_DEFAULT_FILE_OFFSET
177 #elif defined(_LARGEFILE_SOURCE) || defined(_LARGEFILE64_SOURCE) /* || defined(__USE_FILE_OFFSET64) */ \
178 /* || (defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)) */ /* || defined(__sgi) */
179 # define FOPEN fopen64
180 # define FSEEK fseeko64
181 # define FSTAT fstat64
183 # define FTELL ftello64
184 # define LSEEK lseek64
197 #ifdef _STLP_USE_UNIX_IO
198 # ifndef MAP_FAILED /* MMAP failure return code */
199 # define MAP_FAILED -1
201 #elif defined (_STLP_USE_UNIX_EMULATION_IO)
202 # define LSEEK _lseek
205 #if !defined(__MSL__) && !defined(__MRC__) && !defined(__SC__) && !defined(_STLP_WCE) //*TY 04/15/2000 - exclude mpw compilers also
206 static ios_base::openmode flag_to_openmode(int mode) {
207 ios_base::openmode ret = ios_base::__default_mode;
209 switch(mode & O_ACCMODE) {
211 ret = ios_base::in; break;
213 ret = ios_base::out; break;
215 ret = ios_base::in | ios_base::out; break;
219 ret |= ios_base::app;
221 # if defined (_STLP_USE_WIN32_IO)
223 ret |= ios_base::binary;
230 _STLP_MOVE_TO_PRIV_NAMESPACE
232 // Helper functions for _Filebuf_base.
234 bool __is_regular_file(_STLP_fd fd) {
236 #if defined (_STLP_UNIX)
239 return FSTAT(fd, &buf) == 0 && S_ISREG(buf.st_mode);
241 #elif defined(__MRC__) || defined(__SC__) //*TY 02/25/2000 - added support for MPW compilers
244 return true; // each file is a regular file under mac os, isn't it? (we don't have fstat())
246 #elif defined(_STLP_USE_UNIX_EMULATION_IO) || defined (_STLP_USE_STDIO_IO)
249 return FSTAT(fd, &buf) == 0 && (buf.st_mode & _S_IFREG) != 0 ;
251 #elif defined (_STLP_USE_WIN32_IO) && !defined(_STLP_WCE)
253 return (GetFileType(fd) & ~FILE_TYPE_REMOTE) == FILE_TYPE_DISK;
256 (void)fd; // dwa 4/27/00 - suppress unused parameter warning
261 // Number of characters in the file.
262 streamoff __file_size(_STLP_fd fd) {
265 #if defined (_STLP_UNIX)
268 if (FSTAT(fd, &buf) == 0 && S_ISREG(buf.st_mode))
269 ret = buf.st_size > 0 ? buf.st_size : 0;
271 #elif defined(__MRC__) || defined(__SC__) //*TY 02/25/2000 - added support for MPW compilers
275 #elif defined(_STLP_USE_UNIX_EMULATION_IO) || defined (_STLP_USE_STDIO_IO)
278 if (FSTAT(fd, &buf) == 0 && (buf.st_mode & _S_IFREG) != 0)
279 ret = buf.st_size > 0 ? buf.st_size : 0;
281 #elif defined (_STLP_USE_WIN32_IO)
284 li.LowPart = GetFileSize(fd, (unsigned long*) &li.HighPart);
285 if (li.LowPart != INVALID_FILE_SIZE || GetLastError() == NO_ERROR)
289 (void)fd; // dwa 4/27/00 - suppress unused parameter warning
294 _STLP_MOVE_TO_STD_NAMESPACE
296 // Visual C++ and Intel use this, but not Metrowerks
297 // Also MinGW, msvcrt.dll (but not crtdll.dll) dependent version
298 #if (!defined (__MSL__) && !defined (_STLP_WCE) && defined (_STLP_MSVC_LIB) && defined (_WIN32)) || \
299 (defined (__MINGW32__) && defined (__MSVCRT__))
301 // fcntl(fileno, F_GETFL) for Microsoft library
302 // 'semi-documented' defines:
303 # define IOINFO_L2E 5
304 # define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
305 # define _pioinfo(i) ( __pioinfo[(i) >> IOINFO_L2E] + \
306 ((i) & (IOINFO_ARRAY_ELTS - 1)) )
307 # define FAPPEND 0x20 // O_APPEND flag
308 # define FTEXT 0x80 // O_TEXT flag
309 // end of 'semi-documented' defines
311 // 'semi-documented' internal structure
314 long osfhnd; // the real os HANDLE
315 char osfile; // file handle flags
316 char pipech; // pipe buffer
318 // multi-threaded locking
320 CRITICAL_SECTION lock;
323 # if defined (__MINGW32__)
324 __MINGW_IMPORT ioinfo * __pioinfo[];
326 extern _CRTIMP ioinfo * __pioinfo[];
329 // end of 'semi-documented' declarations
331 static ios_base::openmode _get_osfflags(int fd, HANDLE oshandle) {
334 dosflags = _pioinfo(fd)->osfile;
336 //the file will be considered as open in binary mode with no append attribute
337 // end of 'semi-documented' stuff
340 if (dosflags & FAPPEND)
343 if (dosflags & FTEXT)
348 // For Read/Write access we have to guess
350 BOOL writeOk = WriteFile(oshandle, &dummy2, 0, &dummy, 0);
351 BOOL readOk = ReadFile(oshandle, &dummy2, 0, &dummy, NULL);
352 if (writeOk && readOk)
359 return flag_to_openmode(mode);
362 #elif defined (__DMC__)
364 # define FHND_APPEND 0x04
365 # define FHND_DEVICE 0x08
366 # define FHND_TEXT 0x10
368 extern "C" unsigned char __fhnd_info[_NFILE];
370 static ios_base::openmode _get_osfflags(int fd, HANDLE oshandle) {
373 if (__fhnd_info[fd] & FHND_APPEND)
376 if (__fhnd_info[fd] & FHND_TEXT == 0)
379 for (FILE *fp = &_iob[0]; fp < &_iob[_NFILE]; fp++) {
380 if ((fileno(fp) == fd) && (fp->_flag & (_IOREAD | _IOWRT | _IORW))) {
381 const int osflags = fp->_flag;
383 if ((osflags & _IOREAD) && !(osflags & _IOWRT) && !(osflags & _IORW))
385 else if ((osflags & _IOWRT) && !(osflags & _IOREAD) && !(osflags & _IORW))
393 return flag_to_openmode(mode);
397 size_t _Filebuf_base::_M_page_size = 4096;
399 _Filebuf_base::_Filebuf_base()
400 : _M_file_id(INVALID_STLP_FD),
401 #if defined (_STLP_USE_WIN32_IO)
406 _M_should_close(false)
409 void _Filebuf_base::_S_initialize() {
410 #if defined (_STLP_UNIX) && !defined (__DJGPP) && !defined (_CRAY)
411 # if defined (__APPLE__)
413 size_t pagesize, len;
415 mib[1] = HW_PAGESIZE;
416 len = sizeof(pagesize);
417 sysctl(mib, 2, &pagesize, &len, NULL, 0);
418 _M_page_size = pagesize;
419 # elif defined (__DJGPP) && defined (_CRAY)
420 _M_page_size = BUFSIZ;
422 _M_page_size = sysconf(_SC_PAGESIZE);
424 #elif defined (_STLP_USE_WIN32_IO)
425 SYSTEM_INFO SystemInfo;
426 GetSystemInfo(&SystemInfo);
427 _M_page_size = SystemInfo.dwPageSize;
428 // might be .dwAllocationGranularity
432 // Return the size of the file. This is a wrapper for stat.
433 // Returns zero if the size cannot be determined or is ill-defined.
434 streamoff _Filebuf_base::_M_file_size() {
435 return _STLP_PRIV __file_size(_M_file_id);
438 bool _Filebuf_base::_M_open(const char* name, ios_base::openmode openmode,
445 #if defined (_STLP_USE_UNIX_IO) || defined (_STLP_USE_UNIX_EMULATION_IO)
448 // Unix makes no distinction between text and binary files.
449 switch(openmode & (~ios_base::ate & ~ios_base::binary)) {
451 case ios_base::out | ios_base::trunc:
452 flags = O_WRONLY | O_CREAT | O_TRUNC;
454 case ios_base::out | ios_base::app:
455 flags = O_WRONLY | O_CREAT | O_APPEND;
459 permission = 0; // Irrelevant unless we're writing.
461 case ios_base::in | ios_base::out:
464 case ios_base::in | ios_base::out | ios_base::trunc:
465 flags = O_RDWR | O_CREAT | O_TRUNC;
467 default: // The above are the only combinations of
468 return false; // flags allowed by the C++ standard.
471 # if defined (_STLP_USE_UNIX_EMULATION_IO)
472 if (openmode & ios_base::binary)
477 file_no = _open(name, flags, permission);
479 file_no = OPEN(name, flags, permission);
480 # endif /* _STLP_USE_UNIX_EMULATION_IO */
487 if (openmode & ios_base::ate)
488 if (LSEEK(file_no, 0, SEEK_END) == -1)
491 #elif defined (_STLP_USE_STDIO_IO)
492 // use FILE-based i/o
495 switch(openmode & (~ios_base::ate)) {
497 case ios_base::out | ios_base::trunc:
501 case ios_base::out | ios_base::binary:
502 case ios_base::out | ios_base::trunc | ios_base::binary:
506 case ios_base::out | ios_base::app:
510 case ios_base::out | ios_base::app | ios_base::binary:
518 case ios_base::in | ios_base::binary:
522 case ios_base::in | ios_base::out:
526 case ios_base::in | ios_base::out | ios_base::binary:
531 case ios_base::in | ios_base::out | ios_base::trunc:
535 case ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary:
539 default: // The above are the only combinations of
540 return false; // flags allowed by the C++ standard.
543 // fbp : TODO : set permissions !
544 (void)permission; // currently unused //*TY 02/26/2000 - added to suppress warning message
545 _M_file = FOPEN(name, flags);
548 file_no = fileno(_M_file);
553 // unset buffering immediately
558 if (openmode & ios_base::ate) {
559 if (FSEEK(_M_file, 0, SEEK_END) == -1)
563 #elif defined (_STLP_USE_WIN32_IO)
564 DWORD dwDesiredAccess, dwCreationDisposition;
565 bool doTruncate = false;
567 switch (openmode & (~ios_base::ate & ~ios_base::binary)) {
569 case ios_base::out | ios_base::trunc:
570 dwDesiredAccess = GENERIC_WRITE;
571 dwCreationDisposition = OPEN_ALWAYS;
572 // boris : even though it is very non-intuitive, standard
573 // requires them both to behave same.
576 case ios_base::out | ios_base::app:
577 dwDesiredAccess = GENERIC_WRITE;
578 dwCreationDisposition = OPEN_ALWAYS;
581 dwDesiredAccess = GENERIC_READ;
582 dwCreationDisposition = OPEN_EXISTING;
583 permission = 0; // Irrelevant unless we're writing.
585 case ios_base::in | ios_base::out:
586 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
587 dwCreationDisposition = OPEN_EXISTING;
589 case ios_base::in | ios_base::out | ios_base::trunc:
590 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
591 dwCreationDisposition = OPEN_ALWAYS;
594 default: // The above are the only combinations of
595 return false; // flags allowed by the C++ standard.
598 DWORD dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
600 # if defined(_STLP_USE_WIDE_INTERFACE)
601 file_no = CreateFile (_STLP_PRIV __ASCIIToWide(name).c_str(),
603 file_no = CreateFileA(name,
605 dwDesiredAccess, dwShareMode, 0,
606 dwCreationDisposition, permission, 0);
608 if (file_no == INVALID_STLP_FD)
611 if ((doTruncate && SetEndOfFile(file_no) == 0) ||
612 (((openmode & ios_base::ate) != 0) &&
613 (SetFilePointer(file_no, 0, NULL, FILE_END) == INVALID_SET_FILE_POINTER))) {
614 CloseHandle(file_no);
624 _M_file_id = file_no;
625 _M_should_close = _M_is_open;
626 _M_openmode = openmode;
629 _M_regular_file = _STLP_PRIV __is_regular_file(_M_file_id);
631 return (_M_is_open != 0);
635 bool _Filebuf_base::_M_open(const char* name, ios_base::openmode openmode) {
636 // This doesn't really grant everyone in the world read/write
637 // access. On Unix, file-creation system calls always clear
638 // bits that are set in the umask from the permissions flag.
639 #ifdef _STLP_USE_WIN32_IO
640 return this->_M_open(name, openmode, FILE_ATTRIBUTE_NORMAL);
641 #elif defined(__MRC__) || defined(__SC__) //*TY 02/26/2000 - added support for MPW compilers
642 return this->_M_open(name, openmode, 0);
644 return this->_M_open(name, openmode, S_IRUSR | S_IWUSR | S_IRGRP |
645 S_IWGRP | S_IROTH | S_IWOTH);
650 #if defined (_STLP_USE_WIN32_IO)
651 bool _Filebuf_base::_M_open(_STLP_fd __id, ios_base::openmode init_mode) {
652 # if (defined (_STLP_MSVC_LIB) && !defined (_STLP_WCE)) || \
653 (defined (__MINGW32__) && defined (__MSVCRT__)) || defined (__DMC__)
655 if (_M_is_open || __id == INVALID_STLP_FD)
658 if (init_mode != ios_base::__default_mode)
659 _M_openmode = init_mode;
661 _M_openmode = _get_osfflags(-1, __id);
665 _M_should_close = false;
666 _M_regular_file = _STLP_PRIV __is_regular_file(_M_file_id);
671 (void)init_mode; // dwa 4/27/00 - suppress unused parameter warning
673 // not available for the API
678 #endif /* _STLP_USE_WIN32_IO */
680 // Associated the filebuf with a file descriptor pointing to an already-
681 // open file. Mode is set to be consistent with the way that the file
683 bool _Filebuf_base::_M_open(int file_no, ios_base::openmode init_mode) {
684 if (_M_is_open || file_no < 0)
687 #if defined (_STLP_UNIX)
688 (void)init_mode; // dwa 4/27/00 - suppress unused parameter warning
690 mode = fcntl(file_no, F_GETFL);
695 _M_openmode = flag_to_openmode(mode);
696 _M_file_id = file_no;
697 #elif defined(__MRC__) || defined(__SC__) //*TY 02/26/2000 - added support for MPW compilers
698 (void)init_mode; // dwa 4/27/00 - suppress unused parameter warning
699 switch (_iob[file_no]._flag & (_IOREAD|_IOWRT|_IORW) )
702 _M_openmode = ios_base::in; break;
704 _M_openmode = ios_base::out; break;
706 _M_openmode = ios_base::in | ios_base::out; break;
710 _M_file_id = file_no;
711 #elif defined (_STLP_USE_UNIX_EMULATION_IO) || defined (_STLP_USE_STDIO_IO)
712 (void)init_mode; // dwa 4/27/00 - suppress unused parameter warning
715 if (FSTAT(file_no, &buf) != 0)
719 switch(mode & (_S_IWRITE | _S_IREAD) ) {
721 _M_openmode = ios_base::in; break;
723 _M_openmode = ios_base::out; break;
724 case (_S_IWRITE | _S_IREAD):
725 _M_openmode = ios_base::in | ios_base::out; break;
729 _M_file_id = file_no;
730 #elif (defined (_STLP_USE_WIN32_IO) && defined (_STLP_MSVC_LIB) && !defined (_STLP_WCE) ) || \
731 (defined (__MINGW32__) && defined (__MSVCRT__)) || \
734 HANDLE oshandle = (HANDLE)_get_osfhandle(file_no);
735 if (oshandle == INVALID_STLP_FD)
738 if (init_mode != ios_base::__default_mode)
739 _M_openmode = init_mode;
741 _M_openmode = _get_osfflags(file_no, oshandle);
743 _M_file_id = oshandle;
745 (void)init_mode; // dwa 4/27/00 - suppress unused parameter warning
746 // not available for the API
747 # define _STLP_NO_IMPLEMENTATION
750 #if !defined (_STLP_NO_IMPLEMENTATION)
752 _M_should_close = false;
753 _M_regular_file = _STLP_PRIV __is_regular_file(_M_file_id);
756 # undef _STLP_NO_IMPLEMENTATION
761 bool _Filebuf_base::_M_close() {
767 if (!_M_should_close)
771 #if defined (_STLP_USE_UNIX_IO)
773 ok = (close(_M_file_id) == 0);
775 #elif defined (_STLP_USE_UNIX_EMULATION_IO)
777 ok = (_close(_M_file_id) == 0);
779 #elif defined (_STLP_USE_STDIO_IO)
781 ok = (fclose(_M_file) == 0);
783 #elif defined (_STLP_USE_WIN32_IO)
785 if (_M_file_id != INVALID_STLP_FD) {
786 ok = (CloseHandle(_M_file_id) != 0);
796 #endif /* _STLP_USE_UNIX_IO */
799 _M_is_open = _M_should_close = false;
807 #define _STLP_CTRLZ 26
809 // Read up to n characters into a buffer. Return value is number of
811 ptrdiff_t _Filebuf_base::_M_read(char* buf, ptrdiff_t n) {
812 #if defined (_STLP_USE_UNIX_IO)
814 return read(_M_file_id, buf, n);
816 #elif defined (_STLP_USE_UNIX_EMULATION_IO)
818 return _read(_M_file_id, buf, n);
820 #elif defined (_STLP_USE_WIN32_IO)
821 ptrdiff_t readen = 0;
822 //Here cast to size_t is safe as n cannot be negative.
823 size_t chunkSize = (min)(size_t(0xffffffff), __STATIC_CAST(size_t, n));
824 // The following, while validating that we are still able to extract chunkSize
825 // charaters to the buffer, avoids extraction of too small chunk of datas
826 // which would be counter performant.
827 while (__STATIC_CAST(size_t, (n - readen)) >= chunkSize) {
828 DWORD NumberOfBytesRead;
829 ReadFile(_M_file_id, buf + readen, __STATIC_CAST(DWORD, chunkSize), &NumberOfBytesRead, 0);
831 if (NumberOfBytesRead == 0)
834 if (!(_M_openmode & ios_base::binary)) {
835 // translate CR-LFs to LFs in the buffer
836 char *to = buf + readen;
838 char *last = from + NumberOfBytesRead - 1;
839 for (; from <= last && *from != _STLP_CTRLZ; ++from) {
840 if (*from != _STLP_CR)
843 if (from < last) { // not at buffer end
844 if (*(from + 1) != _STLP_LF)
847 else { // last char is CR, peek for LF
849 DWORD NumberOfBytesPeeked;
850 ReadFile(_M_file_id, (LPVOID)&peek, 1, &NumberOfBytesPeeked, 0);
851 if (NumberOfBytesPeeked != 0) {
852 if (peek != _STLP_LF) { //not a <CR><LF> combination
854 if ((to < buf + n) && (peek != _STLP_CR))
855 //We have enough place to store peek and it is no a special
856 //_STLP_CR character, we can store it.
859 SetFilePointer(_M_file_id, (LONG)-1, 0, SEEK_CUR);
862 // A <CR><LF> combination, we keep the <LF>:
867 /* This case is tedious, we could
868 * - put peek back in the file but this would then generate an infinite loop
869 * - report an error as we don't know if in a future call to ReadFile we won't then
870 * get a <LF>. Doing so would make all files with a <CR> last an invalid file
871 * for STLport, a hard solution for STLport clients.
872 * - store the <CR> in the returned buffer, the chosen solution, even if in this
873 * case we could miss a <CR><LF> combination.
880 // seek back to TEXT end of file if hit CTRL-Z
881 if (from <= last) // terminated due to CTRLZ
882 SetFilePointer(_M_file_id, (LONG)((last+1) - from), 0, SEEK_CUR);
883 readen += to - (buf + readen);
886 readen += NumberOfBytesRead;
890 #elif defined (_STLP_USE_STDIO_IO)
892 return fread(buf, 1, n, _M_file);
899 // Write n characters from a buffer. Return value: true if we managed
900 // to write the entire buffer, false if we didn't.
901 bool _Filebuf_base::_M_write(char* buf, ptrdiff_t n) {
905 #if defined (_STLP_USE_UNIX_IO)
907 written = write(_M_file_id, buf, n);
909 #elif defined (_STLP_USE_UNIX_EMULATION_IO)
911 written = _write(_M_file_id, buf, n);
913 #elif defined (_STLP_USE_WIN32_IO)
915 //In the following implementation we are going to cast most of the ptrdiff_t
916 //values in size_t to work with coherent unsigned values. Doing so make code
917 //more simple especially in the min function call.
919 // In append mode, every write does an implicit seek to the end
921 if (_M_openmode & ios_base::app)
922 _M_seek(0, ios_base::end);
924 if (_M_openmode & ios_base::binary) {
926 size_t bytes_to_write = (size_t)n;
927 DWORD NumberOfBytesWritten;
929 for (; bytes_to_write != 0;) {
930 WriteFile(_M_file_id, buf + written,
931 __STATIC_CAST(DWORD, (min)(size_t(0xffffffff), bytes_to_write)),
932 &NumberOfBytesWritten, 0);
933 if (NumberOfBytesWritten == 0)
935 bytes_to_write -= NumberOfBytesWritten;
936 written += NumberOfBytesWritten;
940 char textbuf[_TEXTBUF_SIZE + 1]; // extra 1 in case LF at end
941 char * nextblock = buf, * ptrtextbuf = textbuf;
942 char * endtextbuf = textbuf + _TEXTBUF_SIZE;
943 char * endblock = buf + n;
944 ptrdiff_t nextblocksize = (min) (n, (ptrdiff_t)_TEXTBUF_SIZE);
947 while ( (nextblocksize > 0) &&
948 (nextlf = (char *)memchr(nextblock, _STLP_LF, nextblocksize)) != 0) {
949 ptrdiff_t linelength = nextlf - nextblock;
950 memcpy(ptrtextbuf, nextblock, linelength);
951 ptrtextbuf += linelength;
952 nextblock += (linelength + 1);
953 * ptrtextbuf ++ = _STLP_CR;
954 * ptrtextbuf ++ = _STLP_LF;
955 nextblocksize = (min) (ptrdiff_t(endblock - nextblock),
956 (max) (ptrdiff_t(0), ptrdiff_t(endtextbuf - ptrtextbuf)));
958 // write out what's left, > condition is here since for LF at the end ,
959 // endtextbuf may get < ptrtextbuf ...
960 if (nextblocksize > 0) {
961 memcpy(ptrtextbuf, nextblock, nextblocksize);
962 ptrtextbuf += nextblocksize;
963 nextblock += nextblocksize;
965 // now write out the translated buffer
966 char * writetextbuf = textbuf;
967 for (size_t NumberOfBytesToWrite = (size_t)(ptrtextbuf - textbuf);
968 NumberOfBytesToWrite;) {
969 DWORD NumberOfBytesWritten;
970 WriteFile((HANDLE)_M_file_id, writetextbuf,
971 __STATIC_CAST(DWORD, (min)(size_t(0xffffffff), NumberOfBytesToWrite)),
972 &NumberOfBytesWritten, 0);
973 if (!NumberOfBytesWritten) // write shortfall
975 writetextbuf += NumberOfBytesWritten;
976 NumberOfBytesToWrite -= NumberOfBytesWritten;
978 // count non-translated characters
979 written = (nextblock - buf);
982 #elif defined (_STLP_USE_STDIO_IO)
984 written = fwrite(buf, 1, n, _M_file);
992 else if (written > 0 && written < n) {
1002 #ifdef _STLP_USE_WIN32_IO
1003 # define STL_SEEK_SET FILE_BEGIN
1004 # define STL_SEEK_CUR FILE_CURRENT
1005 # define STL_SEEK_END FILE_END
1007 # define STL_SEEK_SET SEEK_SET
1008 # define STL_SEEK_CUR SEEK_CUR
1009 # define STL_SEEK_END SEEK_END
1012 // Wrapper for lseek or the like.
1013 streamoff _Filebuf_base::_M_seek(streamoff offset, ios_base::seekdir dir) {
1014 streamoff result = -1;
1019 if (offset < 0 /* || offset > _M_file_size() */ )
1020 return streamoff(-1);
1021 whence = STL_SEEK_SET;
1024 whence = STL_SEEK_CUR;
1027 if (/* offset > 0 || */ -offset > _M_file_size() )
1028 return streamoff(-1);
1029 whence = STL_SEEK_END;
1032 return streamoff(-1);
1035 #if defined (_STLP_USE_UNIX_IO) || defined (_STLP_USE_UNIX_EMULATION_IO)
1037 result = LSEEK(_M_file_id, offset, whence);
1039 #elif defined (_STLP_USE_STDIO_IO)
1041 result = FSEEK(_M_file, offset, whence);
1043 #elif defined (_STLP_USE_WIN32_IO)
1046 li.QuadPart = offset;
1047 li.LowPart = SetFilePointer(_M_file_id, li.LowPart, &li.HighPart, whence);
1048 if (li.LowPart != INVALID_SET_FILE_POINTER || GetLastError() == NO_ERROR)
1049 result = li.QuadPart;
1059 // Attempts to memory-map len bytes of the current file, starting
1060 // at position offset. Precondition: offset is a multiple of the
1061 // page size. Postcondition: return value is a null pointer if the
1062 // memory mapping failed. Otherwise the return value is a pointer to
1063 // the memory-mapped file and the file position is set to offset.
1064 void* _Filebuf_base::_M_mmap(streamoff offset, streamoff len) {
1066 #if defined (_STLP_UNIX) && !defined(__DJGPP) && !defined(_CRAY)
1067 base = MMAP(0, len, PROT_READ, MAP_PRIVATE, _M_file_id, offset);
1068 if (base != (void*)MAP_FAILED) {
1069 if (LSEEK(_M_file_id, offset + len, SEEK_SET) < 0) {
1070 this->_M_unmap(base, len);
1076 #elif defined (_STLP_USE_WIN32_IO)
1077 _M_view_id = CreateFileMapping(_M_file_id, (PSECURITY_ATTRIBUTES)0 ,
1078 PAGE_READONLY, 0 /* len >> 32 */ ,
1079 0 /* len & 0xFFFFFFFF */ , // low-order DWORD of size
1085 printf("view %x created from file %x, error = %d, size = %d, map_offset = %d map_len = %d\n",
1086 _M_view_id, _M_file_id, GetLastError(),
1087 (int)cur_filesize, ULL(offset) & 0xffffffff, len);
1090 base = MapViewOfFile(_M_view_id, FILE_MAP_READ, __STATIC_CAST(DWORD, ULL(offset) >> 32),
1091 __STATIC_CAST(DWORD, ULL(offset) & 0xffffffff),
1092 # if !defined (__DMC__)
1093 __STATIC_CAST(SIZE_T, len));
1095 __STATIC_CAST(DWORD, len));
1097 // check if mapping succeded and is usable
1098 if (base == 0 || _M_seek(offset + len, ios_base::beg) < 0) {
1099 this->_M_unmap(base, len);
1105 (void)len; //*TY 02/26/2000 - unused variables
1106 (void)offset; //*TY 02/26/2000 -
1112 void _Filebuf_base::_M_unmap(void* base, streamoff len) {
1113 // precondition : there is a valid mapping at the moment
1114 #if defined (_STLP_UNIX) && !defined(__DJGPP) && !defined(_CRAY)
1115 munmap((char*)base, len);
1116 #elif defined (_STLP_USE_WIN32_IO)
1118 UnmapViewOfFile(base);
1119 // destroy view handle as well
1120 if (_M_view_id != NULL)
1121 CloseHandle(_M_view_id);
1123 (void)len; //unused variable
1125 (void)len; //*TY 02/26/2000 - unused variables
1126 (void)base; //*TY 02/26/2000 -
1130 // fbp : let us map 1 MB maximum, just be sure not to trash VM
1131 #define MMAP_CHUNK 0x100000L
1134 _Underflow<char, char_traits<char> >::_M_doit (basic_filebuf<char, char_traits<char> >* __this) {
1135 if (!__this->_M_in_input_mode) {
1136 if (!__this->_M_switch_to_input_mode())
1137 return traits_type::eof();
1139 else if (__this->_M_in_putback_mode) {
1140 __this->_M_exit_putback_mode();
1141 if (__this->gptr() != __this->egptr()) {
1142 int_type __c = traits_type::to_int_type(*__this->gptr());
1147 // If it's a disk file, and if the internal and external character
1148 // sequences are guaranteed to be identical, then try to use memory
1149 // mapped I/O. Otherwise, revert to ordinary read.
1150 if (__this->_M_base.__regular_file()
1151 && __this->_M_always_noconv
1152 && __this->_M_base._M_in_binary_mode()) {
1153 // If we've mmapped part of the file already, then unmap it.
1154 if (__this->_M_mmap_base)
1155 __this->_M_base._M_unmap(__this->_M_mmap_base, __this->_M_mmap_len);
1156 __this->_M_mmap_base = 0;
1157 __this->_M_mmap_len = 0;
1159 // Determine the position where we start mapping. It has to be
1160 // a multiple of the page size.
1161 streamoff __cur = __this->_M_base._M_seek(0, ios_base::cur);
1162 streamoff __size = __this->_M_base._M_file_size();
1163 if (__size > 0 && __cur >= 0 && __cur < __size) {
1164 streamoff __offset = (__cur / __this->_M_base.__page_size()) * __this->_M_base.__page_size();
1165 streamoff __remainder = __cur - __offset;
1167 __this->_M_mmap_len = __size - __offset;
1169 if (__this->_M_mmap_len > MMAP_CHUNK)
1170 __this->_M_mmap_len = MMAP_CHUNK;
1172 if ((__this->_M_mmap_base =
1173 __this->_M_base._M_mmap(__offset, __this->_M_mmap_len)) != 0) {
1174 __this->setg((char*) __this->_M_mmap_base,
1175 (char*) __this->_M_mmap_base + __STATIC_CAST(ptrdiff_t, __remainder),
1176 (char*) __this->_M_mmap_base + __STATIC_CAST(ptrdiff_t, __this->_M_mmap_len));
1177 return traits_type::to_int_type(*__this->gptr());
1179 } else /* size > 0 ... */ {
1180 // There is nothing to map. We unmapped the file above, now zap pointers.
1181 __this->_M_mmap_base = 0;
1182 __this->_M_mmap_len = 0;
1186 return __this->_M_underflow_aux();
1190 //----------------------------------------------------------------------
1191 // Force instantiation of filebuf and fstream classes.
1192 #if !defined(_STLP_NO_FORCE_INSTANTIATE)
1194 template class basic_filebuf<char, char_traits<char> >;
1195 template class basic_ifstream<char, char_traits<char> >;
1196 template class basic_ofstream<char, char_traits<char> >;
1197 template class basic_fstream<char, char_traits<char> >;
1199 # if !defined (_STLP_NO_WCHAR_T)
1200 template class _Underflow<wchar_t, char_traits<wchar_t> >;
1201 template class basic_filebuf<wchar_t, char_traits<wchar_t> >;
1202 template class basic_ifstream<wchar_t, char_traits<wchar_t> >;
1203 template class basic_ofstream<wchar_t, char_traits<wchar_t> >;
1204 template class basic_fstream<wchar_t, char_traits<wchar_t> >;
1205 # endif /* _STLP_NO_WCHAR_T */