1 /****************************************************************************
4 ** Implementation of QTextStream class
8 ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
10 ** This file is part of the tools module of the Qt GUI Toolkit.
12 ** This file may be distributed under the terms of the Q Public License
13 ** as defined by Trolltech AS of Norway and appearing in the file
14 ** LICENSE.QPL included in the packaging of this file.
16 ** This file may be distributed and/or modified under the terms of the
17 ** GNU General Public License version 2 as published by the Free Software
18 ** Foundation and appearing in the file LICENSE.GPL included in the
19 ** packaging of this file.
21 ** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
22 ** licenses may use this file in accordance with the Qt Commercial License
23 ** Agreement provided with the Software.
25 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
26 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
28 ** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
29 ** information about Qt Commercial License Agreements.
30 ** See http://www.trolltech.com/qpl/ for QPL licensing information.
31 ** See http://www.trolltech.com/gpl/ for GPL licensing information.
33 ** Contact info@trolltech.com if any conditions of this licensing are
36 **********************************************************************/
38 #include "qtextstream.h"
40 #ifndef QT_NO_TEXTSTREAM
41 #include "qtextcodec.h"
49 #if defined(_OS_WIN32_)
55 \class QTextStream qtextstream.h
57 \brief The QTextStream class provides basic functions for reading and
58 writing text using a QIODevice.
70 The text stream class has a functional interface that is very
71 similar to that of the standard C++ iostream class. The difference
72 between iostream and QTextStream is that our stream operates on a
73 QIODevice, which is easily subclassed, while iostream operates on
74 FILE * pointers, which can not be subclassed.
76 Qt provides several global functions similar to the ones in iostream:
78 <li> \c bin sets the QTextStream to read/write binary numbers
79 <li> \c oct sets the QTextStream to read/write octal numbers
80 <li> \c dec sets the QTextStream to read/write decimal numbers
81 <li> \c hex sets the QTextStream to read/write hexadecimal numbers
82 <li> \c endl forces a line break
83 <li> \c flush forces the QIODevice to flush any buffered data
84 <li> \c ws eats any available white space (on input)
85 <li> \c reset resets the QTextStream to its default mode (see reset()).
88 \warning By default, QTextStream will automatically detect whether
89 integers in the stream are in decimal, octal, hexadecimal or binary
90 format when reading from the stream. In particular, a leading '0'
91 signifies octal, ie. the sequence "0100" will be interpreted as
94 The QTextStream class reads and writes text and it is not
95 appropriate for dealing with binary data (but QDataStream is).
97 By default output of Unicode text (ie. QString) is done using the
98 local 8-bit encoding. This can be changed using the setEncoding()
99 method. For input, the QTextStream will auto-detect standard
100 Unicode "byte order marked" text files, but otherwise the local
101 8-bit encoding is used.
107 \class QTSManip qtextstream.h
109 \brief The QTSManip class is an internal helper class for the
112 It is generally a very bad idea to use this class directly in
113 application programs.
117 This class makes it possible to give the QTextStream function objects
118 with arguments, like this:
120 QTextStream cout( stdout, IO_WriteOnly );
121 cout << setprecision( 8 ); // QTSManip used here!
122 cout << 3.14159265358979323846;
125 The setprecision() function returns a QTSManip object.
126 The QTSManip object contains a pointer to a member function in
127 QTextStream and an integer argument.
128 When serializing a QTSManip into a QTextStream, the function
129 is executed with the argument.
132 /*! \fn QTSManip::QTSManip (QTSMFI m, int a)
134 Constructs a QTSManip object which will call \a m (a member function
135 in QTextStream which accepts a single int) with argument \a a when
136 QTSManip::exec() is called. Used internally in e.g. endl:
139 s << "some text" << endl << "more text";
143 /*! \fn void QTSManip::exec (QTextStream& s)
145 Calls the member function specified in the constructor, for object
146 \a s. Used internally in e.g. endl:
149 s << "some text" << endl << "more text";
154 /*****************************************************************************
155 QTextStream member functions
156 *****************************************************************************/
158 #if defined(CHECK_STATE)
159 #undef CHECK_STREAM_PRECOND
160 #define CHECK_STREAM_PRECOND if ( !dev ) { \
161 qWarning( "QTextStream: No device" ); \
164 #define CHECK_STREAM_PRECOND
168 #define I_SHORT 0x0010
170 #define I_LONG 0x0030
171 #define I_TYPE_MASK 0x00f0
173 #define I_BASE_2 QTS::bin
174 #define I_BASE_8 QTS::oct
175 #define I_BASE_10 QTS::dec
176 #define I_BASE_16 QTS::hex
177 #define I_BASE_MASK (QTS::bin | QTS::oct | QTS::dec | QTS::hex)
179 #define I_SIGNED 0x0100
180 #define I_UNSIGNED 0x0200
181 #define I_SIGN_MASK 0x0f00
184 static const QChar QEOF = QChar((ushort)0xffff); //guaranteed not to be a character.
186 const int QTextStream::basefield = I_BASE_MASK;
187 const int QTextStream::adjustfield = ( QTextStream::left |
189 QTextStream::internal );
190 const int QTextStream::floatfield = ( QTextStream::scientific |
191 QTextStream::fixed );
194 class QTextStreamPrivate {
196 #ifndef QT_NO_TEXTCODEC
197 QTextStreamPrivate() : decoder( 0 ), sourceType( NotSet ) {}
198 ~QTextStreamPrivate() { delete decoder; }
199 QTextDecoder *decoder; //???
201 QTextStreamPrivate() : sourceType( NotSet ) {}
202 ~QTextStreamPrivate() { }
206 enum SourceType { NotSet, IODevice, String, ByteArray, File };
207 SourceType sourceType;
211 // skips whitespace and returns the first non-whitespace character
212 QChar QTextStream::eat_ws()
215 do { c = ts_getc(); } while ( c != QEOF && ts_isspace(c) );
219 void QTextStream::init()
221 // ### ungetcBuf = QEOF;
222 dev = 0; // no device set
223 fstrm = owndev = FALSE;
225 d = new QTextStreamPrivate;
226 doUnicodeHeader = TRUE; //default to autodetect
227 latin1 = TRUE; // ### should use local?
228 internalOrder = QChar::networkOrdered(); //default to network order
232 Constructs a data stream that has no IO device.
235 QTextStream::QTextStream()
238 setEncoding( Locale ); //###
240 d->sourceType = QTextStreamPrivate::NotSet;
244 Constructs a text stream that uses the IO device \a iod.
247 QTextStream::QTextStream( QIODevice *iod )
250 setEncoding( Locale ); //###
251 dev = iod; // set device
253 d->sourceType = QTextStreamPrivate::IODevice;
256 // TODO: use special-case handling of this case in QTextStream, and
257 // simplify this class to only deal with QChar or QString data.
258 class QStringBuffer : public QIODevice {
260 QStringBuffer( QString* str );
268 int readBlock( char *p, uint len );
269 int writeBlock( const char *p, uint len );
272 int ungetch( int ch );
276 private: // Disabled copy constructor and operator=
277 QStringBuffer( const QStringBuffer & );
278 QStringBuffer &operator=( const QStringBuffer & );
282 QStringBuffer::QStringBuffer( QString* str )
287 QStringBuffer::~QStringBuffer()
292 bool QStringBuffer::open( int m )
295 #if defined(CHECK_STATE)
296 qWarning( "QStringBuffer::open: No string" );
300 if ( isOpen() ) { // buffer already open
301 #if defined(CHECK_STATE)
302 qWarning( "QStringBuffer::open: Buffer already open" );
307 if ( m & IO_Truncate ) { // truncate buffer
310 if ( m & IO_Append ) { // append to end of buffer
311 ioIndex = s->length()*(int)sizeof(QChar);
320 void QStringBuffer::close()
323 setFlags( IO_Direct );
328 void QStringBuffer::flush()
332 uint QStringBuffer::size() const
334 return s ? s->length()*(int)sizeof(QChar) : 0;
337 int QStringBuffer::at() const
342 bool QStringBuffer::at( int pos )
344 #if defined(CHECK_STATE)
346 qWarning( "QStringBuffer::at: Buffer is not open" );
350 if ( (uint)pos >= s->length()*2 ) {
351 #if defined(CHECK_RANGE)
352 qWarning( "QStringBuffer::at: Index %d out of range", pos );
361 int QStringBuffer::readBlock( char *p, uint len )
363 #if defined(CHECK_STATE)
365 if ( !isOpen() ) { // buffer not open
366 qWarning( "QStringBuffer::readBlock: Buffer not open" );
369 if ( !isReadable() ) { // reading not permitted
370 qWarning( "QStringBuffer::readBlock: Read operation not permitted" );
374 if ( (uint)ioIndex + len > s->length()*sizeof(QChar) ) {
376 if ( (uint)ioIndex >= s->length()*sizeof(QChar) ) {
377 setStatus( IO_ReadError );
380 len = s->length()*2 - (uint)ioIndex;
383 memcpy( p, ((const char*)(s->unicode()))+ioIndex, len );
388 int QStringBuffer::writeBlock( const char *p, uint len )
390 #if defined(CHECK_NULL)
391 if ( p == 0 && len != 0 )
392 qWarning( "QStringBuffer::writeBlock: Null pointer error" );
394 #if defined(CHECK_STATE)
395 if ( !isOpen() ) { // buffer not open
396 qWarning( "QStringBuffer::writeBlock: Buffer not open" );
399 if ( !isWritable() ) { // writing not permitted
400 qWarning( "QStringBuffer::writeBlock: Write operation not permitted" );
404 qWarning( "QStringBuffer::writeBlock: non-even index - non Unicode" );
408 qWarning( "QStringBuffer::writeBlock: non-even length - non Unicode" );
412 s->replace(ioIndex/2, len/2, (QChar*)p, len/2);
417 int QStringBuffer::getch()
419 #if defined(CHECK_STATE)
420 if ( !isOpen() ) { // buffer not open
421 qWarning( "QStringBuffer::getch: Buffer not open" );
424 if ( !isReadable() ) { // reading not permitted
425 qWarning( "QStringBuffer::getch: Read operation not permitted" );
429 if ( (uint)ioIndex >= s->length()*2 ) { // overflow
430 setStatus( IO_ReadError );
433 return *((char*)s->unicode() + ioIndex++);
436 int QStringBuffer::putch( int ch )
439 if ( writeBlock(&c,1) < 0 )
445 int QStringBuffer::ungetch( int ch )
447 #if defined(CHECK_STATE)
448 if ( !isOpen() ) { // buffer not open
449 qWarning( "QStringBuffer::ungetch: Buffer not open" );
452 if ( !isReadable() ) { // reading not permitted
453 qWarning( "QStringBuffer::ungetch: Read operation not permitted" );
457 if ( ch != -1 ) { // something to do with eof
468 Constructs a text stream that operates on a Unicode QString through an
471 If you set an encoding or codec with setEncoding() or setCodec(), this
472 setting is ignored for text streams that operate on QString.
477 QTextStream ts( &str, IO_WriteOnly );
478 ts << "pi = " << 3.14; // str == "pi = 3.14"
481 Writing data to the text stream will modify the contents of the string.
482 The string will be expanded when data is written beyond the end of the
483 string. Note that the string will not be truncated:
485 QString str = "pi = 3.14";
486 QTextStream ts( &str, IO_WriteOnly );
487 ts << "2+2 = " << 2+2; // str == "2+2 = 414"
490 Note that since QString is Unicode, you should not use readRawBytes()
491 or writeRawBytes() on such a stream.
494 QTextStream::QTextStream( QString* str, int filemode )
496 // TODO: optimize for this case as it becomes more common
497 // (see QStringBuffer above)
499 dev = new QStringBuffer( str );
500 ((QStringBuffer *)dev)->open( filemode );
502 setEncoding(RawUnicode);
504 d->sourceType = QTextStreamPrivate::String;
509 This constructor is equivalent to the constructor taking a QString*
513 QTextStream::QTextStream( QString& str, int filemode )
516 dev = new QStringBuffer( &str );
517 ((QStringBuffer *)dev)->open( filemode );
519 setEncoding(RawUnicode);
521 d->sourceType = QTextStreamPrivate::String;
525 Constructs a text stream that operates on a byte array through an
526 internal QBuffer device.
531 QTextStream ts( array, IO_WriteOnly );
532 ts << "pi = " << 3.14 << '\0'; // array == "pi = 3.14"
535 Writing data to the text stream will modify the contents of the array.
536 The array will be expanded when data is written beyond the end of the
539 Same example, using a QBuffer:
542 QBuffer buf( array );
543 buf.open( IO_WriteOnly );
544 QTextStream ts( &buf );
545 ts << "pi = " << 3.14 << '\0'; // array == "pi = 3.14"
550 QTextStream::QTextStream( QByteArray a, int mode )
553 dev = new QBuffer( a );
554 ((QBuffer *)dev)->open( mode );
556 setEncoding( Locale ); //### Locale???
558 d->sourceType = QTextStreamPrivate::ByteArray;
562 Constructs a text stream that operates on an existing file handle \e fh
563 through an internal QFile device.
567 QTextStream cout( stdout, IO_WriteOnly );
568 QTextStream cin ( stdin, IO_ReadOnly );
569 QTextStream cerr( stderr, IO_WriteOnly );
573 QTextStream::QTextStream( FILE *fh, int mode )
576 setEncoding( Locale ); //###
578 ((QFile *)dev)->open( mode, fh );
579 fstrm = owndev = TRUE;
581 d->sourceType = QTextStreamPrivate::File;
585 Destructs the text stream.
587 The destructor does not affect the current IO device.
590 QTextStream::~QTextStream()
598 Positions the read pointer at the first non-whitespace character.
600 void QTextStream::skipWhiteSpace()
602 ts_ungetc( eat_ws() );
607 \fn Encoding QTextStream::encoding() const
609 Returns the encoding mode of the stream.
615 Tries to read len characters from the stream and stores them in \a buf.
616 Returns the number of characters really read.
617 Attention: There will no QEOF appended if the read reaches the end of
618 the file. EOF is reached when the return value does not equal \a len.
620 uint QTextStream::ts_getbuf( QChar* buf, uint len )
625 uint rnum=0; // the number of QChars really read
627 if ( d && d->ungetcBuf.length() ) {
628 while( rnum < len && rnum < d->ungetcBuf.length() ) {
629 buf[rnum] = d->ungetcBuf.constref(rnum);
632 d->ungetcBuf = d->ungetcBuf.mid( rnum );
637 // we use dev->ungetch() for one of the bytes of the unicode
638 // byte-order mark, but a local unget hack for the other byte:
641 if ( doUnicodeHeader ) {
642 doUnicodeHeader = FALSE; //only at the top
643 int c1 = dev->getch();
646 int c2 = dev->getch();
647 if ( c1 == 0xfe && c2 == 0xff ) {
650 internalOrder = QChar::networkOrdered(); //network order
651 } else if ( c1 == 0xff && c2 == 0xfe ) {
654 internalOrder = !QChar::networkOrdered(); //reverse network order
661 // note that a small possible bug might hide here
662 // here, if only the first byte of a file has made it
663 // so far, and that first byte is half of the
664 // byte-order mark, then the utfness will not be
665 // detected. whether or not this is a bug depends on
666 // taste. I can't really decide.
671 #ifndef QT_NO_TEXTCODEC
673 bool shortRead = FALSE;
675 d->decoder = mapper->makeDecoder();
676 while( rnum < len ) {
678 bool readBlock = !( len == 1+rnum );
680 // for efficiency: normally read a whole block
682 // guess buffersize; this may be wrong (too small or too
683 // big). But we can handle this (either iterate reading
684 // or use ungetcBuf).
685 // Note that this might cause problems for codecs where
686 // one byte can result in >1 Unicode Characters if bytes
687 // are written to the stream in the meantime (loss of
689 uint rlen = len - rnum;
690 char *cbuf = new char[ rlen ];
691 if ( ungetHack != EOF ) {
692 rlen = 1+dev->readBlock( cbuf+1, rlen-1 );
693 cbuf[0] = (char)ungetHack;
696 rlen = dev->readBlock( cbuf, rlen );
698 s += d->decoder->toUnicode( cbuf, rlen );
700 // use buffered reading only for the first time, because we
701 // have to get the stream synchronous again (this is easier
702 // with single character reading)
705 // get stream (and codec) in sync
707 if ( ungetHack == EOF ) {
718 uint lengthBefore = s.length();
719 s += d->decoder->toUnicode( &b, 1 );
720 if ( s.length() > lengthBefore )
721 break; // it seems we are in sync now
724 while( rnum < len && i < s.length() )
725 buf[rnum++] = s.constref(i++);
726 if ( s.length() > i )
727 // could be = but append is clearer
728 d->ungetcBuf.append( s.mid( i ) );
735 if ( len == 1+rnum ) {
736 // use this method for one character because it is more efficient
737 // (arnt doubts whether it makes a difference, but lets it stand)
738 int c = (ungetHack == EOF) ? dev->getch() : ungetHack;
740 buf[rnum++] = (char)c;
742 if ( ungetHack != EOF ) {
743 buf[rnum++] = (char)ungetHack;
746 char *cbuf = new char[len - rnum];
747 while ( !dev->atEnd() && rnum < len ) {
748 uint rlen = len - rnum;
749 rlen = dev->readBlock( cbuf, rlen );
752 buf[rnum++] = cbuf[i++];
756 } else { // UCS-2 or UTF-16
757 if ( len == 1+rnum ) {
758 int c1 = (ungetHack == EOF) ? dev->getch() : ungetHack;
761 int c2 = dev->getch();
764 if ( isNetworkOrder() )
765 buf[rnum++] = QChar( c2, c1 );
767 buf[rnum++] = QChar( c1, c2 );
769 char *cbuf = new char[ 2*( len - rnum ) ]; // for paranoids: overflow possible
770 while ( !dev->atEnd() && rnum < len ) {
771 uint rlen = 2 * ( len-rnum );
772 if ( ungetHack != EOF ) {
773 rlen = 1+dev->readBlock( cbuf+1, rlen-1 );
774 cbuf[0] = (char)ungetHack;
777 rlen = dev->readBlock( cbuf, rlen );
779 // We can't use an odd number of bytes, so put it back. But
780 // do it only if we are capable of reading more -- normally
781 // there should not be an odd number, but the file might be
782 // truncated or not in UTF-16...
783 if ( (rlen & 1) == 1 )
785 dev->ungetch( cbuf[--rlen] );
787 if ( isNetworkOrder() ) {
789 buf[rnum++] = QChar( cbuf[i+1], cbuf[i] );
794 buf[rnum++] = QChar( cbuf[i], cbuf[i+1] );
807 Puts one character to the stream.
809 void QTextStream::ts_putc( QChar c )
811 #ifndef QT_NO_TEXTCODEC
815 QCString block = mapper->fromUnicode( s, len );
816 dev->writeBlock( block, len );
821 dev->putch( '?' ); //######unknown character???
823 dev->putch( c.cell() );
825 if ( doUnicodeHeader ) {
826 doUnicodeHeader = FALSE;
827 ts_putc( QChar::byteOrderMark );
829 if ( internalOrder ) {
830 dev->writeBlock( (char*)&c, sizeof(QChar) );
831 } else if ( isNetworkOrder() ) {
833 dev->putch(c.cell());
835 dev->putch(c.cell());
842 Puts one character to the stream.
844 void QTextStream::ts_putc(int ch)
846 ts_putc(QChar((ushort)ch));
849 bool QTextStream::ts_isdigit(QChar c)
854 bool QTextStream::ts_isspace( QChar c )
859 void QTextStream::ts_ungetc( QChar c )
861 if ( c.unicode() == 0xffff )
864 d->ungetcBuf.prepend( c );
870 Reads \e len bytes from the stream into \e e s and returns a reference to
873 The buffer \e s must be preallocated.
875 Note that no encoding is done by this function.
877 \warning The behaviour of this function is undefined unless the
878 stream's encoding is set to Unicode or Latin1.
880 \sa QIODevice::readBlock()
883 QTextStream &QTextStream::readRawBytes( char *s, uint len )
885 dev->readBlock( s, len );
890 Writes the \e len bytes from \e s to the stream and returns a reference to
893 Note that no encoding is done by this function.
895 \sa QIODevice::writeBlock()
898 QTextStream &QTextStream::writeRawBytes( const char* s, uint len )
900 dev->writeBlock( s, len );
905 QTextStream &QTextStream::writeBlock( const char* p, uint len )
907 if ( doUnicodeHeader ) {
908 doUnicodeHeader = FALSE;
909 if ( !mapper && !latin1 )
910 ts_putc( QChar::byteOrderMark );
912 //All QCStrings and const char* are defined to be in Latin1
913 if ( !mapper && latin1 ) {
914 dev->writeBlock( p, len );
915 } else if ( !mapper && internalOrder ) {
916 QChar *u = new QChar[len];
917 for (uint i=0; i<len; i++)
919 dev->writeBlock( (char*)u, len*(int)sizeof(QChar) );
922 for (uint i=0; i<len; i++)
923 ts_putc( (uchar)p[i] );
928 QTextStream &QTextStream::writeBlock( const QChar* p, uint len )
930 if ( !mapper && !latin1 && internalOrder ) {
931 if ( doUnicodeHeader ) {
932 doUnicodeHeader = FALSE;
933 ts_putc( QChar::byteOrderMark );
935 dev->writeBlock( (char*)p, (int)sizeof(QChar)*len );
937 for (uint i=0; i<len; i++)
946 Resets the text stream.
949 <li> All flags are set to 0.
950 <li> The field width is set to 0.
951 <li> The fill character is set to ' ' (space).
952 <li> The precision is set to 6.
955 \sa setf(), width(), fill(), precision()
958 void QTextStream::reset()
968 \fn QIODevice *QTextStream::device() const
969 Returns the IO device currently set.
970 \sa setDevice(), unsetDevice()
974 Sets the IO device to \a iod.
975 \sa device(), unsetDevice()
978 void QTextStream::setDevice( QIODevice *iod )
985 d->sourceType = QTextStreamPrivate::IODevice;
989 Unsets the IO device. Equivalent to setDevice( 0 ).
990 \sa device(), setDevice()
993 void QTextStream::unsetDevice()
996 d->sourceType = QTextStreamPrivate::NotSet;
1000 \fn bool QTextStream::atEnd() const
1001 Returns TRUE if the IO device has reached the end position (end of
1002 stream or file) or if there is no IO device set.
1004 Returns FALSE if the current position of the read/write head of the IO
1005 device is somewhere before the end position.
1007 \sa QIODevice::atEnd()
1010 /*!\fn bool QTextStream::eof() const
1014 This function has been renamed to atEnd().
1016 \sa QIODevice::atEnd()
1019 /*****************************************************************************
1020 QTextStream read functions
1021 *****************************************************************************/
1025 Reads a \c char from the stream and returns a reference to the stream.
1026 Note that whitespace is skipped.
1029 QTextStream &QTextStream::operator>>( char &c )
1031 CHECK_STREAM_PRECOND
1037 Reads a \c char from the stream and returns a reference to the stream.
1038 Note that whitespace is \e not skipped.
1041 QTextStream &QTextStream::operator>>( QChar &c )
1043 CHECK_STREAM_PRECOND
1049 ulong QTextStream::input_bin()
1052 QChar ch = eat_ws();
1053 int dv = ch.digitValue();
1054 while ( dv == 0 || dv == 1 ) {
1055 val = ( val << 1 ) + dv;
1057 dv = ch.digitValue();
1064 ulong QTextStream::input_oct()
1067 QChar ch = eat_ws();
1068 int dv = ch.digitValue();
1069 while ( dv >= 0 && dv <= 7 ) {
1070 val = ( val << 3 ) + dv;
1072 dv = ch.digitValue();
1074 if ( dv == 8 || dv == 9 ) {
1075 while ( ts_isdigit(ch) )
1083 ulong QTextStream::input_dec()
1086 QChar ch = eat_ws();
1087 int dv = ch.digitValue();
1088 while ( ts_isdigit(ch) ) {
1089 val = val * 10 + dv;
1091 dv = ch.digitValue();
1098 ulong QTextStream::input_hex()
1101 QChar ch = eat_ws();
1103 while ( isxdigit(c) ) {
1105 if ( ts_isdigit(c) )
1108 val += 10 + tolower(c) - 'a';
1116 long QTextStream::input_int()
1121 switch ( flags() & basefield ) {
1123 val = (long)input_bin();
1126 val = (long)input_oct();
1133 if ( !(c == '-' || c == '+') )
1136 ulong v = input_dec();
1137 if ( v ) { // ensure that LONG_MIN can be read
1139 val = -((long)v) - 1;
1144 val = (long)input_dec();
1149 val = (long)input_hex();
1154 if ( c == '0' ) { // bin, oct or hex
1156 if ( tolower(c) == 'x' )
1157 val = (long)input_hex();
1158 else if ( tolower(c) == 'b' )
1159 val = (long)input_bin();
1162 if ( c >= '0' && c <= '7' ) {
1163 val = (long)input_oct();
1168 } else if ( ts_isdigit(ch) ) {
1170 val = (long)input_dec();
1171 } else if ( c == '-' || c == '+' ) {
1172 ulong v = input_dec();
1174 if ( v ) { // ensure that LONG_MIN can be read
1176 val = -((long)v) - 1;
1189 // We use a table-driven FSM to parse floating point numbers
1190 // strtod() cannot be used directly since we're reading from a QIODevice
1193 double QTextStream::input_double()
1195 const int Init = 0; // states
1197 const int Mantissa = 2;
1199 const int Abscissa = 4;
1200 const int ExpMark = 5;
1201 const int ExpSign = 6;
1202 const int Exponent = 7;
1205 const int InputSign = 1; // input tokens
1206 const int InputDigit = 2;
1207 const int InputDot = 3;
1208 const int InputExp = 4;
1210 static uchar table[8][5] = {
1211 /* None InputSign InputDigit InputDot InputExp */
1212 { 0, Sign, Mantissa, Dot, 0, }, // Init
1213 { 0, 0, Mantissa, Dot, 0, }, // Sign
1214 { Done, Done, Mantissa, Dot, ExpMark,}, // Mantissa
1215 { 0, 0, Abscissa, 0, 0, }, // Dot
1216 { Done, Done, Abscissa, Done, ExpMark,}, // Abscissa
1217 { 0, ExpSign, Exponent, 0, 0, }, // ExpMark
1218 { 0, 0, Exponent, 0, 0, }, // ExpSign
1219 { Done, Done, Exponent, Done, Done } // Exponent
1222 int state = Init; // parse state
1223 int input; // input token
1236 case '0': case '1': case '2': case '3': case '4':
1237 case '5': case '6': case '7': case '8': case '9':
1252 state = table[state][input];
1254 if ( state == 0 || state == Done || i > 250 ) {
1255 if ( i > 250 ) { // ignore rest of digits
1256 do { c = ts_getc(); } while ( c != QEOF && ts_isdigit(c) );
1262 return strtod( buf, &end );
1269 #if !defined(_CC_EGG_)
1276 Reads a signed \c short integer from the stream and returns a reference to
1277 the stream. See flags() for an explanation of expected input format.
1280 QTextStream &QTextStream::operator>>( signed short &i )
1282 CHECK_STREAM_PRECOND
1283 i = (signed short)input_int();
1289 Reads an unsigned \c short integer from the stream and returns a reference to
1290 the stream. See flags() for an explanation of expected input format.
1293 QTextStream &QTextStream::operator>>( unsigned short &i )
1295 CHECK_STREAM_PRECOND
1296 i = (unsigned short)input_int();
1302 Reads a signed \c int from the stream and returns a reference to the
1303 stream. See flags() for an explanation of expected input format.
1306 QTextStream &QTextStream::operator>>( signed int &i )
1308 CHECK_STREAM_PRECOND
1309 i = (signed int)input_int();
1315 Reads an unsigned \c int from the stream and returns a reference to the
1316 stream. See flags() for an explanation of expected input format.
1319 QTextStream &QTextStream::operator>>( unsigned int &i )
1321 CHECK_STREAM_PRECOND
1322 i = (unsigned int)input_int();
1328 Reads a signed \c long int from the stream and returns a reference to the
1329 stream. See flags() for an explanation of expected input format.
1332 QTextStream &QTextStream::operator>>( signed long &i )
1334 CHECK_STREAM_PRECOND
1335 i = (signed long)input_int();
1341 Reads an unsigned \c long int from the stream and returns a reference to the
1342 stream. See flags() for an explanation of expected input format.
1345 QTextStream &QTextStream::operator>>( unsigned long &i )
1347 CHECK_STREAM_PRECOND
1348 i = (unsigned long)input_int();
1354 Reads a \c float from the stream and returns a reference to the stream.
1355 See flags() for an explanation of expected input format.
1358 QTextStream &QTextStream::operator>>( float &f )
1360 CHECK_STREAM_PRECOND
1361 f = (float)input_double();
1367 Reads a \c double from the stream and returns a reference to the stream.
1368 See flags() for an explanation of expected input format.
1371 QTextStream &QTextStream::operator>>( double &f )
1373 CHECK_STREAM_PRECOND
1380 Reads a word from the stream and returns a reference to the stream.
1383 QTextStream &QTextStream::operator>>( char *s )
1385 CHECK_STREAM_PRECOND
1386 int maxlen = width( 0 );
1390 while ( c != QEOF ) {
1391 if ( ts_isspace(c) || maxlen-- == 0 ) {
1404 Reads a word from the stream and returns a reference to the stream.
1407 QTextStream &QTextStream::operator>>( QString &str )
1409 CHECK_STREAM_PRECOND
1410 str=QString::fromLatin1("");
1413 while ( c != QEOF ) {
1414 if ( ts_isspace(c) ) {
1425 Reads a word from the stream and returns a reference to the stream.
1428 QTextStream &QTextStream::operator>>( QCString &str )
1430 CHECK_STREAM_PRECOND
1431 QCString *dynbuf = 0;
1432 const int buflen = 256;
1433 char buffer[buflen];
1438 while ( c != QEOF ) {
1439 if ( ts_isspace(c) ) {
1443 if ( i >= buflen-1 ) {
1444 if ( !dynbuf ) { // create dynamic buffer
1445 dynbuf = new QCString(buflen*2);
1446 memcpy( dynbuf->rawData(), s, i ); // copy old data
1447 } else if ( i >= (int)dynbuf->size()-1 ) {
1448 dynbuf->resize( dynbuf->size()*2 );
1450 s = dynbuf->rawData();
1456 memcpy( str.rawData(), s, i );
1463 Reads a line from the stream and returns a string containing the text.
1465 The returned string does not contain any trailing newline or carriage
1466 return. Note that this is different from QIODevice::readLine(), which
1467 does not strip the newline at the end of the line.
1469 On EOF you will get a QString that is null. On reading an empty line the
1470 returned QString is empty but not null.
1472 \sa QIODevice::readLine()
1475 QString QTextStream::readLine()
1477 #if defined(CHECK_STATE)
1479 qWarning( "QTextStream::readLine: No device" );
1480 return QString::null;
1483 QString result( "" );
1484 const int buf_size = 256;
1489 if ( c[pos] == QEOF )
1490 return QString::null;
1492 while ( c[pos] != QEOF && c[pos] != '\n' ) {
1494 if ( pos >= buf_size ) {
1495 result += QString( c, pos );
1500 result += QString( c, pos );
1502 int len = (int)result.length();
1503 if ( len && result[len-1] == '\r' )
1504 result.truncate(len-1); // (if there are two \r, let one stay)
1511 Reads the entire stream and returns a string containing the text.
1513 \sa QIODevice::readLine()
1516 QString QTextStream::read()
1518 #if defined(CHECK_STATE)
1520 qWarning( "QTextStream::read: No device" );
1521 return QString::null;
1525 const uint bufsize = 512;
1528 bool skipped_cr = FALSE;
1531 num = ts_getbuf(buf,bufsize);
1534 for ( i=0; i<num; i++ ) {
1535 if ( buf[i] == '\r' ) {
1536 // Only skip single cr's preceding lf's
1541 result += QString( &buf[start], i-start );
1547 if ( buf[i] != '\n' ) {
1548 // Should not have skipped it
1556 result += QString( &buf[start], i-start );
1557 if ( num != bufsize ) // if ( EOF )
1565 /*****************************************************************************
1566 QTextStream write functions
1567 *****************************************************************************/
1570 Writes a \c char to the stream and returns a reference to the stream.
1572 The character \a c is assumed to be Latin1 encoded independent of the Encoding set
1573 for the QTextStream.
1575 QTextStream &QTextStream::operator<<( QChar c )
1577 CHECK_STREAM_PRECOND
1583 Writes a \c char to the stream and returns a reference to the stream.
1585 QTextStream &QTextStream::operator<<( char c )
1587 CHECK_STREAM_PRECOND
1588 unsigned char uc = (unsigned char) c;
1593 QTextStream &QTextStream::output_int( int format, ulong n, bool neg )
1595 static char hexdigits_lower[] = "0123456789abcdef";
1596 static char hexdigits_upper[] = "0123456789ABCDEF";
1597 CHECK_STREAM_PRECOND
1603 switch ( flags() & I_BASE_MASK ) {
1605 case I_BASE_2: // output binary number
1606 switch ( format & I_TYPE_MASK ) {
1607 case I_SHORT: len=16; break;
1608 case I_INT: len=sizeof(int)*8; break;
1609 case I_LONG: len=32; break;
1612 p = &buf[74]; // go reverse order
1615 *--p = (char)(n&1) + '0';
1620 if ( flags() & showbase ) { // show base
1621 *--p = (flags() & uppercase) ? 'B' : 'b';
1626 case I_BASE_8: // output octal number
1630 *--p = (char)(n&7) + '0';
1633 if ( flags() & showbase )
1637 case I_BASE_16: // output hexadecimal number
1640 hexdigits = (flags() & uppercase) ?
1641 hexdigits_upper : hexdigits_lower;
1643 *--p = hexdigits[(int)n&0xf];
1646 if ( flags() & showbase ) {
1647 *--p = (flags() & uppercase) ? 'X' : 'x';
1652 default: // decimal base is default
1656 n = (ulong)(-(long)n);
1658 *--p = ((int)(n%10)) + '0';
1663 else if ( flags() & showpos )
1665 if ( (flags() & internal) && fwidth && !ts_isdigit(*p) ) {
1666 ts_putc( *p ); // special case for internal
1669 return *this << (const char*)p;
1672 if ( fwidth ) { // adjustment required
1673 if ( !(flags() & left) ) { // but NOT left adjustment
1675 int padlen = fwidth - len;
1676 if ( padlen <= 0 ) { // no padding required
1677 writeBlock( p, len );
1678 } else if ( padlen < (int)(p-buf) ) { // speeds up padding
1679 memset( p-padlen, (char)fillchar, padlen );
1680 writeBlock( p-padlen, padlen+len );
1682 else // standard padding
1683 *this << (const char*)p;
1686 *this << (const char*)p;
1687 fwidth = 0; // reset field width
1690 writeBlock( p, qstrlen(p) );
1696 Writes a \c short integer to the stream and returns a reference to
1700 QTextStream &QTextStream::operator<<( signed short i )
1702 return output_int( I_SHORT | I_SIGNED, i, i < 0 );
1707 Writes an \c unsigned \c short integer to the stream and returns a reference
1711 QTextStream &QTextStream::operator<<( unsigned short i )
1713 return output_int( I_SHORT | I_UNSIGNED, i, FALSE );
1718 Writes an \c int to the stream and returns a reference to
1722 QTextStream &QTextStream::operator<<( signed int i )
1724 return output_int( I_INT | I_SIGNED, i, i < 0 );
1729 Writes an \c unsigned \c int to the stream and returns a reference to
1733 QTextStream &QTextStream::operator<<( unsigned int i )
1735 return output_int( I_INT | I_UNSIGNED, i, FALSE );
1740 Writes a \c long \c int to the stream and returns a reference to
1744 QTextStream &QTextStream::operator<<( signed long i )
1746 return output_int( I_LONG | I_SIGNED, i, i < 0 );
1751 Writes an \c unsigned \c long \c int to the stream and returns a reference to
1755 QTextStream &QTextStream::operator<<( unsigned long i )
1757 return output_int( I_LONG | I_UNSIGNED, i, FALSE );
1762 Writes a \c float to the stream and returns a reference to the stream.
1765 QTextStream &QTextStream::operator<<( float f )
1767 return *this << (double)f;
1772 Writes a \c double to the stream and returns a reference to the stream.
1775 QTextStream &QTextStream::operator<<( double f )
1777 CHECK_STREAM_PRECOND
1781 if ( (flags()&floatfield) == fixed )
1783 else if ( (flags()&floatfield) == scientific )
1784 f_char = (flags() & uppercase) ? 'E' : 'e';
1786 f_char = (flags() & uppercase) ? 'G' : 'g';
1787 char *fs = format; // generate format string
1788 *fs++ = '%'; // "%.<prec>l<f_char>"
1790 int prec = precision();
1794 *fs++ = prec / 10 + '0';
1795 *fs++ = prec % 10 + '0';
1802 sprintf( buf, format, f ); // convert to text
1803 if ( fwidth ) // padding
1804 *this << (const char*)buf;
1805 else // just write it
1806 writeBlock( buf, qstrlen(buf) );
1812 Writes a string to the stream and returns a reference to the stream.
1814 The string \a s is assumed to be Latin1 encoded independent of the Encoding set
1815 for the QTextStream.
1818 QTextStream &QTextStream::operator<<( const char* s )
1820 CHECK_STREAM_PRECOND
1822 uint len = qstrlen( s ); // don't write null terminator
1823 if ( fwidth ) { // field width set
1824 int padlen = fwidth - len;
1825 fwidth = 0; // reset width
1828 if ( padlen > 46 ) { // create extra big fill buffer
1829 ppad = new char[padlen];
1834 memset( ppad, (char)fillchar, padlen ); // fill with fillchar
1835 if ( !(flags() & left) ) {
1836 writeBlock( ppad, padlen );
1839 writeBlock( s, len );
1841 writeBlock( ppad, padlen );
1842 if ( ppad != padbuf ) // delete extra big fill buf
1847 writeBlock( s, len );
1852 Writes \a s to the stream and returns a reference to the stream.
1854 The string \a s is assumed to be Latin1 encoded independent of the Encoding set
1855 for the QTextStream.
1858 QTextStream &QTextStream::operator<<( const QCString & s )
1860 return operator<<(s.data());
1864 Writes \a s to the stream and returns a reference to the stream.
1867 QTextStream &QTextStream::operator<<( const QString& s )
1869 CHECK_STREAM_PRECOND
1870 uint len = s.length();
1872 if ( fwidth ) { // field width set
1873 if ( !(flags() & left) ) {
1874 s1 = s.rightJustify(fwidth, (char)fillchar);
1876 s1 = s.leftJustify(fwidth, (char)fillchar);
1878 fwidth = 0; // reset width
1880 writeBlock( s1.unicode(), len );
1886 Writes a pointer to the stream and returns a reference to the stream.
1888 The \e ptr is output as an unsigned long hexadecimal integer.
1891 QTextStream &QTextStream::operator<<( void *ptr )
1894 setf( hex, basefield );
1896 unsetf( uppercase );
1897 output_int( I_LONG | I_UNSIGNED, (uintptr_t)ptr, FALSE );
1904 \fn int QTextStream::flags() const
1905 Returns the current stream flags. The default value is 0.
1907 The meaning of the flags are:
1909 <li> \e skipws - Not currently used - whitespace always skipped
1910 <li> \e left - Numeric fields are left-aligned
1911 <li> \e right - Not currently used (by default numerics are right aligned)
1912 <li> \e internal - Put any padding spaces between +/- and value
1913 <li> \e bin - Output \e and input only in binary
1914 <li> \e oct - Output \e and input only in octal
1915 <li> \e dec - Output \e and input only in decimal
1916 <li> \e hex - Output \e and input only in hexadecimal
1917 <li> \e showbase - Annotate numeric outputs with 0b, 0, or 0x if in
1918 \e bin, \e oct, or \e hex format
1919 <li> \e showpoint - Not currently used
1920 <li> \e uppercase - Use 0B and 0X rather than 0b and 0x
1921 <li> \e showpos - Show + for positive numeric values
1922 <li> \e scientific - Use scientific notation for floating point values
1923 <li> \e fixed - Use fixed-point notation for floating point values
1926 Note that unless \e bin, \e oct, \e dec, or \e hex is set, the input base is
1927 octal if the value starts with 0, hexadecimal if it starts with 0x, binary
1928 if the value starts with 0b, and decimal otherwise.
1930 \sa setf(), unsetf()
1934 \fn int QTextStream::flags( int f )
1935 Sets the stream flags to \e f.
1936 Returns the previous stream flags.
1938 \sa setf(), unsetf(), flags()
1942 \fn int QTextStream::setf( int bits )
1943 Sets the stream flag bits \e bits.
1944 Returns the previous stream flags.
1946 Equivalent to <code>flags( flags() | bits )</code>.
1948 \sa setf(), unsetf()
1952 \fn int QTextStream::setf( int bits, int mask )
1953 Sets the stream flag bits \e bits with a bit mask \e mask.
1954 Returns the previous stream flags.
1956 Equivalent to <code>flags( (flags() & ~mask) | (bits & mask) )</code>.
1958 \sa setf(), unsetf()
1962 \fn int QTextStream::unsetf( int bits )
1963 Clears the stream flag bits \e bits.
1964 Returns the previous stream flags.
1966 Equivalent to <code>flags( flags() & ~mask )</code>.
1972 \fn int QTextStream::width() const
1973 Returns the field width. The default value is 0.
1977 \fn int QTextStream::width( int w )
1978 Sets the field width to \e w. Returns the previous field width.
1982 \fn int QTextStream::fill() const
1983 Returns the fill character. The default value is ' ' (space).
1987 \fn int QTextStream::fill( int f )
1988 Sets the fill character to \e f. Returns the previous fill character.
1992 \fn int QTextStream::precision() const
1993 Returns the precision. The default value is 6.
1997 \fn int QTextStream::precision( int p )
1998 Sets the precision to \e p. Returns the previous precision setting.
2002 /*****************************************************************************
2003 QTextStream manipulators
2004 *****************************************************************************/
2006 QTextStream &bin( QTextStream &s )
2008 s.setf(QTS::bin,QTS::basefield);
2012 QTextStream &oct( QTextStream &s )
2014 s.setf(QTS::oct,QTS::basefield);
2018 QTextStream &dec( QTextStream &s )
2020 s.setf(QTS::dec,QTS::basefield);
2024 QTextStream &hex( QTextStream &s )
2026 s.setf(QTS::hex,QTS::basefield);
2030 QTextStream &endl( QTextStream &s )
2035 QTextStream &flush( QTextStream &s )
2038 s.device()->flush();
2042 QTextStream &ws( QTextStream &s )
2048 QTextStream &reset( QTextStream &s )
2056 \class QTextIStream qtextstream.h
2057 \brief A convenience class for input streams.
2059 For simple tasks, code should be simple. Hence this
2060 class is a shorthand to avoid passing the \e mode argument
2061 to the normal QTextStream constructors.
2063 This makes it easy for example, to write things like this:
2065 QString data = "123 456";
2067 QTextIStream(&data) >> a >> b;
2074 \fn QTextIStream::QTextIStream( QString *s )
2076 Constructs a stream to read from string \a s.
2079 \fn QTextIStream::QTextIStream( QByteArray ba )
2081 Constructs a stream to read from the array \a ba.
2084 \fn QTextIStream::QTextIStream( FILE *f )
2086 Constructs a stream to read from the file \a f.
2091 \class QTextOStream qtextstream.h
2092 \brief A convenience class for output streams.
2094 For simple tasks, code should be simple. Hence this
2095 class is a shorthand to avoid passing the \e mode argument
2096 to the normal QTextStream constructors.
2098 This makes it easy for example, to write things like this:
2101 QTextOStream(&result) << "pi = " << 3.14;
2106 \fn QTextOStream::QTextOStream( QString *s )
2108 Constructs a stream to write to string \a s.
2111 \fn QTextOStream::QTextOStream( QByteArray ba )
2113 Constructs a stream to write to the array \a ba.
2116 \fn QTextOStream::QTextOStream( FILE *f )
2118 Constructs a stream to write to the file \a f.
2124 Sets the encoding of this stream to \a e, where \a e is one of:
2126 <li> \c Locale Using local file format (Latin1 if locale is not
2127 set), but autodetecting Unicode(utf16) on input.
2128 <li> \c Unicode Using Unicode(utf16) for input and output. Output
2129 will be written in the order most efficient for the current platform
2130 (i.e. the order used internally in QString).
2131 <li> \c UnicodeUTF8 Using Unicode(utf8) for input and output. If you use it
2132 for input it will autodetect utf16 and use it instead of utf8.
2133 <li> \c Latin1 ISO-8859-1. Will not autodetect utf16.
2134 <li> \c UnicodeNetworkOrder Using network order Unicode(utf16) for
2135 input and output. Useful when reading Unicode data that does not
2136 start with the byte order marker.
2137 <li> \c UnicodeReverse Using reverse network order Unicode(utf16)
2138 for input and output. Useful when reading Unicode data that does not
2139 start with the byte order marker, or writing data that should be
2140 read by buggy Windows applications.
2141 <li> \c RawUnicode Like Unicode, but does not write the byte order
2142 marker, nor does it autodetect the byte order. Only useful when
2143 writing to non-persistent storage used by a single process.
2146 \c Locale and all Unicode encodings, except \c RawUnicode, will look at
2147 the first two bytes in a input stream to determine the byte order. The
2148 initial byte order marker will be stripped off before data is read.
2150 Note that this function should be called before any data is read
2151 to/written from the stream.
2155 void QTextStream::setEncoding( Encoding e )
2157 if ( d->sourceType == QTextStreamPrivate::String )
2158 return; // QString does not need any encoding
2163 doUnicodeHeader = TRUE;
2164 internalOrder = TRUE;
2167 #ifndef QT_NO_CODECS
2168 mapper = QTextCodec::codecForMib( 106 );
2170 doUnicodeHeader = TRUE;
2171 internalOrder = TRUE;
2175 doUnicodeHeader = TRUE;
2178 case UnicodeNetworkOrder:
2181 doUnicodeHeader = TRUE;
2182 internalOrder = QChar::networkOrdered();
2184 case UnicodeReverse:
2187 doUnicodeHeader = TRUE;
2188 internalOrder = !QChar::networkOrdered(); //reverse network ordered
2193 doUnicodeHeader = FALSE;
2194 internalOrder = TRUE;
2197 latin1 = TRUE; // fallback to Latin 1
2198 #ifndef QT_NO_TEXTCODEC
2199 mapper = QTextCodec::codecForLocale();
2200 #if defined(_OS_WIN32_)
2201 if ( GetACP() == 1252 )
2202 mapper = 0; // Optimized latin1 processing
2204 if ( mapper && mapper->mibEnum() == 4 )
2206 mapper = 0; // Optimized latin1 processing
2207 doUnicodeHeader = TRUE; // If it reads as Unicode, accept it
2211 doUnicodeHeader = FALSE;
2218 #ifndef QT_NO_TEXTCODEC
2219 /*! Sets the codec for this stream to \a codec. Will not try to
2222 Note that this function should be called before any data is read
2223 to/written from the stream.
2228 void QTextStream::setCodec( QTextCodec *codec )
2230 if ( d->sourceType == QTextStreamPrivate::String )
2231 return; // QString does not need any codec
2233 doUnicodeHeader = FALSE;
2237 #endif // QT_NO_TEXTSTREAM