1 /****************************************************************************
3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtCore module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
40 ****************************************************************************/
42 //#define QTEXTSTREAM_DEBUG
43 static const int QTEXTSTREAM_BUFFERSIZE
= 16384;
48 \brief The QTextStream class provides a convenient interface for
49 reading and writing text.
52 \ingroup string-processing
55 QTextStream can operate on a QIODevice, a QByteArray or a
56 QString. Using QTextStream's streaming operators, you can
57 conveniently read and write words, lines and numbers. For
58 generating text, QTextStream supports formatting options for field
59 padding and alignment, and formatting of numbers. Example:
61 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 0
63 It's also common to use QTextStream to read console input and write
64 console output. QTextStream is locale aware, and will automatically decode
65 standard input using the correct codec. Example:
67 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 1
69 Note that you cannot use QTextStream::atEnd(), which returns true when you
70 have reached the end of the data stream, with stdin. The reason for this is
71 that as long as stdin doesn't give any input to the QTextStream, \c atEnd()
72 will return true even if the stdin is open and waiting for more characters.
74 Besides using QTextStream's constructors, you can also set the
75 device or string QTextStream operates on by calling setDevice() or
76 setString(). You can seek to a position by calling seek(), and
77 atEnd() will return true when there is no data left to be read. If
78 you call flush(), QTextStream will empty all data from its write
79 buffer into the device and call flush() on the device.
81 Internally, QTextStream uses a Unicode based buffer, and
82 QTextCodec is used by QTextStream to automatically support
83 different character sets. By default, QTextCodec::codecForLocale()
84 is used for reading and writing, but you can also set the codec by
85 calling setCodec(). Automatic Unicode detection is also
86 supported. When this feature is enabled (the default behavior),
87 QTextStream will detect the UTF-16 or the UTF-32 BOM (Byte Order Mark) and
88 switch to the appropriate UTF codec when reading. QTextStream
89 does not write a BOM by default, but you can enable this by calling
90 setGenerateByteOrderMark(true). When QTextStream operates on a QString
91 directly, the codec is disabled.
93 There are three general ways to use QTextStream when reading text
98 \o Chunk by chunk, by calling readLine() or readAll().
100 \o Word by word. QTextStream supports streaming into QStrings,
101 QByteArrays and char* buffers. Words are delimited by space, and
102 leading white space is automatically skipped.
104 \o Character by character, by streaming into QChar or char types.
105 This method is often used for convenient input handling when
106 parsing files, independent of character encoding and end-of-line
107 semantics. To skip white space, call skipWhiteSpace().
111 Since the text stream uses a buffer, you should not read from
112 the stream using the implementation of a superclass. For instance,
113 if you have a QFile and read from it directly using
114 QFile::readLine() instead of using the stream, the text stream's
115 internal position will be out of sync with the file's position.
117 By default, when reading numbers from a stream of text,
118 QTextStream will automatically detect the number's base
119 representation. For example, if the number starts with "0x", it is
120 assumed to be in hexadecimal form. If it starts with the digits
121 1-9, it is assumed to be in decimal form, and so on. You can set
122 the integer base, thereby disabling the automatic detection, by
123 calling setIntegerBase(). Example:
125 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 2
127 QTextStream supports many formatting options for generating text.
128 You can set the field width and pad character by calling
129 setFieldWidth() and setPadChar(). Use setFieldAlignment() to set
130 the alignment within each field. For real numbers, call
131 setRealNumberNotation() and setRealNumberPrecision() to set the
132 notation (SmartNotation, ScientificNotation, FixedNotation) and precision in
133 digits of the generated number. Some extra number formatting
134 options are also available through setNumberFlags().
136 \keyword QTextStream manipulators
138 Like \c <iostream> in the standard C++ library, QTextStream also
139 defines several global manipulator functions:
142 \header \o Manipulator \o Description
143 \row \o \c bin \o Same as setIntegerBase(2).
144 \row \o \c oct \o Same as setIntegerBase(8).
145 \row \o \c dec \o Same as setIntegerBase(10).
146 \row \o \c hex \o Same as setIntegerBase(16).
147 \row \o \c showbase \o Same as setNumberFlags(numberFlags() | ShowBase).
148 \row \o \c forcesign \o Same as setNumberFlags(numberFlags() | ForceSign).
149 \row \o \c forcepoint \o Same as setNumberFlags(numberFlags() | ForcePoint).
150 \row \o \c noshowbase \o Same as setNumberFlags(numberFlags() & ~ShowBase).
151 \row \o \c noforcesign \o Same as setNumberFlags(numberFlags() & ~ForceSign).
152 \row \o \c noforcepoint \o Same as setNumberFlags(numberFlags() & ~ForcePoint).
153 \row \o \c uppercasebase \o Same as setNumberFlags(numberFlags() | UppercaseBase).
154 \row \o \c uppercasedigits \o Same as setNumberFlags(numberFlags() | UppercaseDigits).
155 \row \o \c lowercasebase \o Same as setNumberFlags(numberFlags() & ~UppercaseBase).
156 \row \o \c lowercasedigits \o Same as setNumberFlags(numberFlags() & ~UppercaseDigits).
157 \row \o \c fixed \o Same as setRealNumberNotation(FixedNotation).
158 \row \o \c scientific \o Same as setRealNumberNotation(ScientificNotation).
159 \row \o \c left \o Same as setFieldAlignment(AlignLeft).
160 \row \o \c right \o Same as setFieldAlignment(AlignRight).
161 \row \o \c center \o Same as setFieldAlignment(AlignCenter).
162 \row \o \c endl \o Same as operator<<('\n') and flush().
163 \row \o \c flush \o Same as flush().
164 \row \o \c reset \o Same as reset().
165 \row \o \c ws \o Same as skipWhiteSpace().
166 \row \o \c bom \o Same as setGenerateByteOrderMark(true).
169 In addition, Qt provides three global manipulators that take a
170 parameter: qSetFieldWidth(), qSetPadChar(), and
171 qSetRealNumberPrecision().
173 \sa QDataStream, QIODevice, QFile, QBuffer, QTcpSocket, {Codecs Example}
176 /*! \enum QTextStream::RealNumberNotation
178 This enum specifies which notations to use for expressing \c
179 float and \c double as strings.
181 \value ScientificNotation Scientific notation (\c{printf()}'s \c %e flag).
182 \value FixedNotation Fixed-point notation (\c{printf()}'s \c %f flag).
183 \value SmartNotation Scientific or fixed-point notation, depending on which makes most sense (\c{printf()}'s \c %g flag).
185 \sa setRealNumberNotation()
188 /*! \enum QTextStream::FieldAlignment
190 This enum specifies how to align text in fields when the field is
191 wider than the text that occupies it.
193 \value AlignLeft Pad on the right side of fields.
194 \value AlignRight Pad on the left side of fields.
195 \value AlignCenter Pad on both sides of field.
196 \value AlignAccountingStyle Same as AlignRight, except that the
197 sign of a number is flush left.
199 \sa setFieldAlignment()
202 /*! \enum QTextStream::NumberFlag
204 This enum specifies various flags that can be set to affect the
205 output of integers, \c{float}s, and \c{double}s.
207 \value ShowBase Show the base as a prefix if the base
208 is 16 ("0x"), 8 ("0"), or 2 ("0b").
209 \value ForcePoint Always put the decimal separator in numbers, even if
210 there are no decimals.
211 \value ForceSign Always put the sign in numbers, even for positive numbers.
212 \value UppercaseBase Use uppercase versions of base prefixes ("0X", "0B").
213 \value UppercaseDigits Use uppercase letters for expressing
214 digits 10 to 35 instead of lowercase.
219 /*! \enum QTextStream::Status
221 This enum describes the current status of the text stream.
223 \value Ok The text stream is operating normally.
224 \value ReadPastEnd The text stream has read past the end of the
225 data in the underlying device.
226 \value ReadCorruptData The text stream has read corrupt data.
231 #include "qtextstream.h"
234 #include "qnumeric.h"
235 #ifndef QT_NO_TEXTCODEC
236 #include "qtextcodec.h"
241 #include "private/qlocale_p.h"
247 #if defined QTEXTSTREAM_DEBUG
252 // Returns a human readable representation of the first \a len
253 // characters in \a data.
254 static QByteArray
qt_prettyDebug(const char *data
, int len
, int maxSize
)
256 if (!data
) return "(null)";
258 for (int i
= 0; i
< len
; ++i
) {
260 if (isprint(int(uchar(c
)))) {
263 case '\n': out
+= "\\n"; break;
264 case '\r': out
+= "\\r"; break;
265 case '\t': out
+= "\\t"; break;
268 tmp
.sprintf("\\x%x", (unsigned int)(unsigned char)c
);
269 out
+= tmp
.toLatin1();
282 // A precondition macro
284 #define CHECK_VALID_STREAM(x) do { \
285 if (!d->string && !d->device) { \
286 qWarning("QTextStream: No device"); \
290 // Base implementations of operator>> for ints and reals
291 #define IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(type) do { \
293 CHECK_VALID_STREAM(*this); \
295 switch (d->getNumber(&tmp)) { \
296 case QTextStreamPrivate::npsOk: \
299 case QTextStreamPrivate::npsMissingDigit: \
300 case QTextStreamPrivate::npsInvalidPrefix: \
302 setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData); \
305 return *this; } while (0)
307 #define IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(type) do { \
309 CHECK_VALID_STREAM(*this); \
311 if (d->getReal(&tmp)) { \
315 setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData); \
317 return *this; } while (0)
321 #ifndef QT_NO_QOBJECT
322 class QDeviceClosedNotifier
: public QObject
326 inline QDeviceClosedNotifier()
329 inline void setupDevice(QTextStream
*stream
, QIODevice
*device
)
333 connect(device
, SIGNAL(aboutToClose()), this, SLOT(flushStream()));
334 this->stream
= stream
;
338 inline void flushStream() { stream
->flush(); }
345 //-------------------------------------------------------------------
346 class QTextStreamPrivate
348 Q_DECLARE_PUBLIC(QTextStream
)
350 QTextStreamPrivate(QTextStream
*q_ptr
);
351 ~QTextStreamPrivate();
356 #ifndef QT_NO_QOBJECT
357 QDeviceClosedNotifier deviceClosedNotifier
;
364 QIODevice::OpenMode stringOpenMode
;
366 #ifndef QT_NO_TEXTCODEC
369 QTextCodec::ConverterState readConverterState
;
370 QTextCodec::ConverterState writeConverterState
;
371 QTextCodec::ConverterState
*readConverterSavedState
;
372 bool autoDetectUnicode
;
376 enum TokenDelimiter
{
382 QString
read(int maxlen
);
383 bool scan(const QChar
**ptr
, int *tokenLength
,
384 int maxlen
, TokenDelimiter delimiter
);
385 inline const QChar
*readPtr() const;
386 inline void consumeLastToken();
387 inline void consume(int nchars
);
388 void saveConverterState(qint64 newPos
);
389 void restoreToSavedConverterState();
392 // Return value type for getNumber()
393 enum NumberParsingStatus
{
399 inline bool write(const QString
&data
);
400 inline bool getChar(QChar
*ch
);
401 inline void ungetChar(const QChar
&ch
);
402 NumberParsingStatus
getNumber(qulonglong
*l
);
403 bool getReal(double *f
);
405 bool putNumber(qulonglong number
, bool negative
);
406 inline bool putString(const QString
&ch
, bool number
= false);
409 bool fillReadBuffer(qint64 maxBytes
= -1);
410 void resetReadBuffer();
411 bool flushWriteBuffer();
414 int readBufferOffset
;
415 int readConverterSavedStateOffset
; //the offset between readBufferStartDevicePos and that start of the buffer
416 qint64 readBufferStartDevicePos
;
418 // streaming parameters
419 int realNumberPrecision
;
423 QTextStream::FieldAlignment fieldAlignment
;
424 QTextStream::RealNumberNotation realNumberNotation
;
425 QTextStream::NumberFlags numberFlags
;
428 QTextStream::Status status
;
437 QTextStreamPrivate::QTextStreamPrivate(QTextStream
*q_ptr
)
439 #ifndef QT_NO_TEXTCODEC
440 readConverterSavedState(0),
442 readConverterSavedStateOffset(0),
451 QTextStreamPrivate::~QTextStreamPrivate()
454 #ifndef QT_NO_QOBJECT
455 device
->blockSignals(true);
459 #ifndef QT_NO_TEXTCODEC
460 delete readConverterSavedState
;
464 #ifndef QT_NO_TEXTCODEC
465 static void resetCodecConverterStateHelper(QTextCodec::ConverterState
*state
)
467 state
->~ConverterState();
468 new (state
) QTextCodec::ConverterState
;
471 static void copyConverterStateHelper(QTextCodec::ConverterState
*dest
,
472 const QTextCodec::ConverterState
*src
)
474 // ### QTextCodec::ConverterState's copy constructors and assignments are
475 // private. This function copies the structure manually.
477 dest
->flags
= src
->flags
;
478 dest
->invalidChars
= src
->invalidChars
;
479 dest
->state_data
[0] = src
->state_data
[0];
480 dest
->state_data
[1] = src
->state_data
[1];
481 dest
->state_data
[2] = src
->state_data
[2];
487 void QTextStreamPrivate::reset()
489 realNumberPrecision
= 6;
492 padChar
= QLatin1Char(' ');
493 fieldAlignment
= QTextStream::AlignRight
;
494 realNumberNotation
= QTextStream::SmartNotation
;
498 deleteDevice
= false;
501 stringOpenMode
= QIODevice::NotOpen
;
503 readBufferOffset
= 0;
504 readBufferStartDevicePos
= 0;
507 #ifndef QT_NO_TEXTCODEC
508 codec
= QTextCodec::codecForLocale();
509 resetCodecConverterStateHelper(&readConverterState
);
510 resetCodecConverterStateHelper(&writeConverterState
);
511 delete readConverterSavedState
;
512 readConverterSavedState
= 0;
513 writeConverterState
.flags
|= QTextCodec::IgnoreHeader
;
514 autoDetectUnicode
= true;
520 bool QTextStreamPrivate::fillReadBuffer(qint64 maxBytes
)
522 // no buffer next to the QString itself; this function should only
523 // be called internally, for devices.
527 // handle text translation and bypass the Text flag in the device.
528 bool textModeEnabled
= device
->isTextModeEnabled();
530 device
->setTextModeEnabled(false);
532 // read raw data into a temporary buffer
533 char buf
[QTEXTSTREAM_BUFFERSIZE
];
534 qint64 bytesRead
= 0;
535 #if defined(Q_OS_WIN)
536 // On Windows, there is no non-blocking stdin - so we fall back to reading
537 // lines instead. If there is no QOBJECT, we read lines for all sequential
538 // devices; otherwise, we read lines only for stdin.
541 if (device
->isSequential()
542 #if !defined(QT_NO_QOBJECT)
543 && (file
= qobject_cast
<QFile
*>(device
)) && file
->handle() == 0
547 bytesRead
= device
->readLine(buf
, qMin
<qint64
>(sizeof(buf
), maxBytes
));
549 bytesRead
= device
->readLine(buf
, sizeof(buf
));
554 bytesRead
= device
->read(buf
, qMin
<qint64
>(sizeof(buf
), maxBytes
));
556 bytesRead
= device
->read(buf
, sizeof(buf
));
559 #ifndef QT_NO_TEXTCODEC
560 // codec auto detection, explicitly defaults to locale encoding if the
561 // codec has been set to 0.
562 if (!codec
|| autoDetectUnicode
) {
563 autoDetectUnicode
= false;
565 codec
= QTextCodec::codecForUtfText(QByteArray::fromRawData(buf
, bytesRead
), codec
);
567 codec
= QTextCodec::codecForLocale();
568 writeConverterState
.flags
|= QTextCodec::IgnoreHeader
;
571 #if defined (QTEXTSTREAM_DEBUG)
572 qDebug("QTextStreamPrivate::fillReadBuffer(), using %s codec",
573 codec
->name().constData());
577 #if defined (QTEXTSTREAM_DEBUG)
578 qDebug("QTextStreamPrivate::fillReadBuffer(), device->read(\"%s\", %d) == %d",
579 qt_prettyDebug(buf
, qMin(32,int(bytesRead
)) , int(bytesRead
)).constData(), sizeof(buf
), int(bytesRead
));
585 int oldReadBufferSize
= readBuffer
.size();
586 #ifndef QT_NO_TEXTCODEC
587 // convert to unicode
588 readBuffer
+= codec
->toUnicode(buf
, bytesRead
, &readConverterState
);
590 readBuffer
+= QString::fromLatin1(QByteArray(buf
, bytesRead
).constData());
593 // reset the Text flag.
595 device
->setTextModeEnabled(true);
597 // remove all '\r\n' in the string.
598 if (readBuffer
.size() > oldReadBufferSize
&& textModeEnabled
) {
599 QChar CR
= QLatin1Char('\r');
600 QChar
*writePtr
= readBuffer
.data() + oldReadBufferSize
;
601 QChar
*readPtr
= readBuffer
.data() + oldReadBufferSize
;
602 QChar
*endPtr
= readBuffer
.data() + readBuffer
.size();
604 int n
= oldReadBufferSize
;
605 if (readPtr
< endPtr
) {
606 // Cut-off to avoid unnecessary self-copying.
607 while (*readPtr
++ != CR
) {
609 if (++writePtr
== endPtr
)
613 while (readPtr
< endPtr
) {
614 QChar ch
= *readPtr
++;
618 if (n
< readBufferOffset
)
624 readBuffer
.resize(writePtr
- readBuffer
.data());
627 #if defined (QTEXTSTREAM_DEBUG)
628 qDebug("QTextStreamPrivate::fillReadBuffer() read %d bytes from device. readBuffer = [%s]", int(bytesRead
),
629 qt_prettyDebug(readBuffer
.toLatin1(), readBuffer
.size(), readBuffer
.size()).data());
636 void QTextStreamPrivate::resetReadBuffer()
639 readBufferOffset
= 0;
640 readBufferStartDevicePos
= (device
? device
->pos() : 0);
645 bool QTextStreamPrivate::flushWriteBuffer()
647 // no buffer next to the QString itself; this function should only
648 // be called internally, for devices.
649 if (string
|| !device
)
651 if (writeBuffer
.isEmpty())
654 #if defined (Q_OS_WIN)
655 // handle text translation and bypass the Text flag in the device.
656 bool textModeEnabled
= device
->isTextModeEnabled();
657 if (textModeEnabled
) {
658 device
->setTextModeEnabled(false);
659 writeBuffer
.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
663 #ifndef QT_NO_TEXTCODEC
665 codec
= QTextCodec::codecForLocale();
666 #if defined (QTEXTSTREAM_DEBUG)
667 qDebug("QTextStreamPrivate::flushWriteBuffer(), using %s codec (%s generating BOM)",
668 codec
->name().constData(), writeConverterState
.flags
& QTextCodec::IgnoreHeader
? "not" : "");
671 // convert from unicode to raw data
672 QByteArray data
= codec
->fromUnicode(writeBuffer
.data(), writeBuffer
.size(), &writeConverterState
);
674 QByteArray data
= writeBuffer
.toLocal8Bit();
678 // write raw data to the device
679 qint64 bytesWritten
= device
->write(data
);
680 #if defined (QTEXTSTREAM_DEBUG)
681 qDebug("QTextStreamPrivate::flushWriteBuffer(), device->write(\"%s\") == %d",
682 qt_prettyDebug(data
.constData(), qMin(data
.size(),32), data
.size()).constData(), int(bytesWritten
));
684 if (bytesWritten
<= 0)
687 #if defined (Q_OS_WIN)
688 // replace the text flag
690 device
->setTextModeEnabled(true);
694 #ifndef QT_NO_QOBJECT
695 QFile
*file
= qobject_cast
<QFile
*>(device
);
696 bool flushed
= file
&& file
->flush();
701 #if defined (QTEXTSTREAM_DEBUG)
702 qDebug("QTextStreamPrivate::flushWriteBuffer() wrote %d bytes",
705 return flushed
&& bytesWritten
== qint64(data
.size());
708 QString
QTextStreamPrivate::read(int maxlen
)
712 lastTokenSize
= qMin(maxlen
, string
->size() - stringOffset
);
713 ret
= string
->mid(stringOffset
, lastTokenSize
);
715 while (readBuffer
.size() - readBufferOffset
< maxlen
&& fillReadBuffer()) ;
716 lastTokenSize
= qMin(maxlen
, readBuffer
.size() - readBufferOffset
);
717 ret
= readBuffer
.mid(readBufferOffset
, lastTokenSize
);
721 #if defined (QTEXTSTREAM_DEBUG)
722 qDebug("QTextStreamPrivate::read() maxlen = %d, token length = %d", maxlen
, ret
.length());
729 Scans no more than \a maxlen QChars in the current buffer for the
730 first \a delimiter. Stores a pointer to the start offset of the
731 token in \a ptr, and the length in QChars in \a length.
733 bool QTextStreamPrivate::scan(const QChar
**ptr
, int *length
, int maxlen
, TokenDelimiter delimiter
)
737 bool consumeDelimiter
= false;
738 bool foundToken
= false;
739 int startOffset
= device
? readBufferOffset
: stringOffset
;
742 bool canStillReadFromDevice
= true;
747 chPtr
= readBuffer
.constData();
748 endOffset
= readBuffer
.size();
750 chPtr
= string
->constData();
751 endOffset
= string
->size();
753 chPtr
+= startOffset
;
755 for (; !foundToken
&& startOffset
< endOffset
&& (!maxlen
|| totalSize
< maxlen
); ++startOffset
) {
756 const QChar ch
= *chPtr
++;
773 if (ch
== QLatin1Char('\n')) {
775 delimSize
= (lastChar
== QLatin1Char('\r')) ? 2 : 1;
776 consumeDelimiter
= true;
783 && (!maxlen
|| totalSize
< maxlen
)
784 && (device
&& (canStillReadFromDevice
= fillReadBuffer())));
786 // if the token was not found, but we reached the end of input,
787 // then we accept what we got. if we are not at the end of input,
789 if (!foundToken
&& (!maxlen
|| totalSize
< maxlen
)
791 || (string
&& stringOffset
+ totalSize
< string
->size())
792 || (device
&& !device
->atEnd() && canStillReadFromDevice
))) {
793 #if defined (QTEXTSTREAM_DEBUG)
794 qDebug("QTextStreamPrivate::scan() did not find the token.");
799 // if we find a '\r' at the end of the data when reading lines,
800 // don't make it part of the line.
801 if (delimiter
== EndOfLine
&& totalSize
> 0 && !foundToken
) {
802 if (((string
&& stringOffset
+ totalSize
== string
->size()) || (device
&& device
->atEnd()))
803 && lastChar
== QLatin1Char('\r')) {
804 consumeDelimiter
= true;
809 // set the read offset and length of the token
811 *length
= totalSize
- delimSize
;
815 // update last token size. the callee will call consumeLastToken() when
817 lastTokenSize
= totalSize
;
818 if (!consumeDelimiter
)
819 lastTokenSize
-= delimSize
;
821 #if defined (QTEXTSTREAM_DEBUG)
822 qDebug("QTextStreamPrivate::scan(%p, %p, %d, %x) token length = %d, delimiter = %d",
823 ptr
, length
, maxlen
, (int)delimiter
, totalSize
- delimSize
, delimSize
);
830 inline const QChar
*QTextStreamPrivate::readPtr() const
832 Q_ASSERT(readBufferOffset
<= readBuffer
.size());
834 return string
->constData() + stringOffset
;
835 return readBuffer
.constData() + readBufferOffset
;
840 inline void QTextStreamPrivate::consumeLastToken()
843 consume(lastTokenSize
);
849 inline void QTextStreamPrivate::consume(int size
)
851 #if defined (QTEXTSTREAM_DEBUG)
852 qDebug("QTextStreamPrivate::consume(%d)", size
);
855 stringOffset
+= size
;
856 if (stringOffset
> string
->size())
857 stringOffset
= string
->size();
859 readBufferOffset
+= size
;
860 if (readBufferOffset
>= readBuffer
.size()) {
861 readBufferOffset
= 0;
863 saveConverterState(device
->pos());
864 } else if (readBufferOffset
> QTEXTSTREAM_BUFFERSIZE
) {
865 readBuffer
= readBuffer
.remove(0,readBufferOffset
);
866 readConverterSavedStateOffset
+= readBufferOffset
;
867 readBufferOffset
= 0;
874 inline void QTextStreamPrivate::saveConverterState(qint64 newPos
)
876 #ifndef QT_NO_TEXTCODEC
877 if (readConverterState
.d
) {
878 // converter cannot be copied, so don't save anything
879 // don't update readBufferStartDevicePos either
883 if (!readConverterSavedState
)
884 readConverterSavedState
= new QTextCodec::ConverterState
;
885 copyConverterStateHelper(readConverterSavedState
, &readConverterState
);
888 readBufferStartDevicePos
= newPos
;
889 readConverterSavedStateOffset
= 0;
894 inline void QTextStreamPrivate::restoreToSavedConverterState()
896 #ifndef QT_NO_TEXTCODEC
897 if (readConverterSavedState
) {
898 // we have a saved state
899 // that means the converter can be copied
900 copyConverterStateHelper(&readConverterState
, readConverterSavedState
);
902 // the only state we could save was the initial
904 resetCodecConverterStateHelper(&readConverterState
);
911 inline bool QTextStreamPrivate::write(const QString
&data
)
914 // ### What about seek()??
915 string
->append(data
);
918 if (writeBuffer
.size() > QTEXTSTREAM_BUFFERSIZE
)
919 return flushWriteBuffer();
926 inline bool QTextStreamPrivate::getChar(QChar
*ch
)
928 if ((string
&& stringOffset
== string
->size())
929 || (device
&& readBuffer
.isEmpty() && !fillReadBuffer())) {
942 inline void QTextStreamPrivate::ungetChar(const QChar
&ch
)
945 if (stringOffset
== 0)
948 (*string
)[--stringOffset
] = ch
;
952 if (readBufferOffset
== 0) {
953 readBuffer
.prepend(ch
);
957 readBuffer
[--readBufferOffset
] = ch
;
962 inline bool QTextStreamPrivate::putString(const QString
&s
, bool number
)
967 int padSize
= fieldWidth
- s
.size();
969 QString
pad(padSize
, padChar
);
970 if (fieldAlignment
== QTextStream::AlignLeft
) {
971 tmp
.append(QString(padSize
, padChar
));
972 } else if (fieldAlignment
== QTextStream::AlignRight
973 || fieldAlignment
== QTextStream::AlignAccountingStyle
) {
974 tmp
.prepend(QString(padSize
, padChar
));
975 if (fieldAlignment
== QTextStream::AlignAccountingStyle
&& number
) {
976 const QChar sign
= s
.size() > 0 ? s
.at(0) : QChar();
977 if (sign
== locale
.negativeSign() || sign
== locale
.positiveSign()) {
978 QChar
*data
= tmp
.data();
979 data
[padSize
] = tmp
.at(0);
983 } else if (fieldAlignment
== QTextStream::AlignCenter
) {
984 tmp
.prepend(QString(padSize
/2, padChar
));
985 tmp
.append(QString(padSize
- padSize
/2, padChar
));
989 #if defined (QTEXTSTREAM_DEBUG)
990 QByteArray a
= s
.toUtf8();
991 QByteArray b
= tmp
.toUtf8();
992 qDebug("QTextStreamPrivate::putString(\"%s\") calls write(\"%s\")",
993 qt_prettyDebug(a
.constData(), a
.size(), qMax(16, a
.size())).constData(),
994 qt_prettyDebug(b
.constData(), b
.size(), qMax(16, b
.size())).constData());
1000 Constructs a QTextStream. Before you can use it for reading or
1001 writing, you must assign a device or a string.
1003 \sa setDevice(), setString()
1005 QTextStream::QTextStream()
1006 : d_ptr(new QTextStreamPrivate(this))
1008 #if defined (QTEXTSTREAM_DEBUG)
1009 qDebug("QTextStream::QTextStream()");
1016 Constructs a QTextStream that operates on \a device.
1018 QTextStream::QTextStream(QIODevice
*device
)
1019 : d_ptr(new QTextStreamPrivate(this))
1021 #if defined (QTEXTSTREAM_DEBUG)
1022 qDebug("QTextStream::QTextStream(QIODevice *device == *%p)",
1027 #ifndef QT_NO_QOBJECT
1028 d
->deviceClosedNotifier
.setupDevice(this, d
->device
);
1034 Constructs a QTextStream that operates on \a string, using \a
1035 openMode to define the open mode.
1037 QTextStream::QTextStream(QString
*string
, QIODevice::OpenMode openMode
)
1038 : d_ptr(new QTextStreamPrivate(this))
1040 #if defined (QTEXTSTREAM_DEBUG)
1041 qDebug("QTextStream::QTextStream(QString *string == *%p, openMode = %d)",
1042 string
, int(openMode
));
1046 d
->stringOpenMode
= openMode
;
1051 Constructs a QTextStream that operates on \a array, using \a
1052 openMode to define the open mode. Internally, the array is wrapped
1055 QTextStream::QTextStream(QByteArray
*array
, QIODevice::OpenMode openMode
)
1056 : d_ptr(new QTextStreamPrivate(this))
1058 #if defined (QTEXTSTREAM_DEBUG)
1059 qDebug("QTextStream::QTextStream(QByteArray *array == *%p, openMode = %d)",
1060 array
, int(openMode
));
1063 d
->device
= new QBuffer(array
);
1064 d
->device
->open(openMode
);
1065 d
->deleteDevice
= true;
1066 #ifndef QT_NO_QOBJECT
1067 d
->deviceClosedNotifier
.setupDevice(this, d
->device
);
1073 Constructs a QTextStream that operates on \a array, using \a
1074 openMode to define the open mode. The array is accessed as
1075 read-only, regardless of the values in \a openMode.
1077 This constructor is convenient for working on constant
1080 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 3
1082 QTextStream::QTextStream(const QByteArray
&array
, QIODevice::OpenMode openMode
)
1083 : d_ptr(new QTextStreamPrivate(this))
1085 #if defined (QTEXTSTREAM_DEBUG)
1086 qDebug("QTextStream::QTextStream(const QByteArray &array == *(%p), openMode = %d)",
1087 &array
, int(openMode
));
1089 QBuffer
*buffer
= new QBuffer
;
1090 buffer
->setData(array
);
1091 buffer
->open(openMode
);
1095 d
->deleteDevice
= true;
1096 #ifndef QT_NO_QOBJECT
1097 d
->deviceClosedNotifier
.setupDevice(this, d
->device
);
1103 Constructs a QTextStream that operates on \a fileHandle, using \a
1104 openMode to define the open mode. Internally, a QFile is created
1105 to handle the FILE pointer.
1107 This constructor is useful for working directly with the common
1108 FILE based input and output streams: stdin, stdout and stderr. Example:
1110 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 4
1113 QTextStream::QTextStream(FILE *fileHandle
, QIODevice::OpenMode openMode
)
1114 : d_ptr(new QTextStreamPrivate(this))
1116 #if defined (QTEXTSTREAM_DEBUG)
1117 qDebug("QTextStream::QTextStream(FILE *fileHandle = %p, openMode = %d)",
1118 fileHandle
, int(openMode
));
1120 QFile
*file
= new QFile
;
1121 file
->open(fileHandle
, openMode
);
1125 d
->deleteDevice
= true;
1126 #ifndef QT_NO_QOBJECT
1127 d
->deviceClosedNotifier
.setupDevice(this, d
->device
);
1133 Destroys the QTextStream.
1135 If the stream operates on a device, flush() will be called
1136 implicitly. Otherwise, the device is unaffected.
1138 QTextStream::~QTextStream()
1141 #if defined (QTEXTSTREAM_DEBUG)
1142 qDebug("QTextStream::~QTextStream()");
1144 if (!d
->writeBuffer
.isEmpty())
1145 d
->flushWriteBuffer();
1149 Resets QTextStream's formatting options, bringing it back to its
1150 original constructed state. The device, string and any buffered
1151 data is left untouched.
1153 void QTextStream::reset()
1157 d
->realNumberPrecision
= 6;
1160 d
->padChar
= QLatin1Char(' ');
1161 d
->fieldAlignment
= QTextStream::AlignRight
;
1162 d
->realNumberNotation
= QTextStream::SmartNotation
;
1167 Flushes any buffered data waiting to be written to the device.
1169 If QTextStream operates on a string, this function does nothing.
1171 void QTextStream::flush()
1174 d
->flushWriteBuffer();
1178 Seeks to the position \a pos in the device. Returns true on
1179 success; otherwise returns false.
1181 bool QTextStream::seek(qint64 pos
)
1184 d
->lastTokenSize
= 0;
1187 // Empty the write buffer
1188 d
->flushWriteBuffer();
1189 if (!d
->device
->seek(pos
))
1191 d
->resetReadBuffer();
1193 #ifndef QT_NO_TEXTCODEC
1194 // Reset the codec converter states.
1195 resetCodecConverterStateHelper(&d
->readConverterState
);
1196 resetCodecConverterStateHelper(&d
->writeConverterState
);
1197 delete d
->readConverterSavedState
;
1198 d
->readConverterSavedState
= 0;
1204 if (d
->string
&& pos
<= d
->string
->size()) {
1205 d
->stringOffset
= int(pos
);
1214 Returns the device position corresponding to the current position of the
1215 stream, or -1 if an error occurs (e.g., if there is no device or string,
1216 or if there's a device error).
1218 Because QTextStream is buffered, this function may have to
1219 seek the device to reconstruct a valid device position. This
1220 operation can be expensive, so you may want to avoid calling this
1221 function in a tight loop.
1225 qint64
QTextStream::pos() const
1227 Q_D(const QTextStream
);
1230 if (d
->readBuffer
.isEmpty())
1231 return d
->device
->pos();
1232 if (d
->device
->isSequential())
1236 if (!d
->device
->seek(d
->readBufferStartDevicePos
))
1239 // Reset the read buffer
1240 QTextStreamPrivate
*thatd
= const_cast<QTextStreamPrivate
*>(d
);
1241 thatd
->readBuffer
.clear();
1243 #ifndef QT_NO_TEXTCODEC
1244 thatd
->restoreToSavedConverterState();
1245 if (d
->readBufferStartDevicePos
== 0)
1246 thatd
->autoDetectUnicode
= true;
1249 // Rewind the device to get to the current position Ensure that
1250 // readBufferOffset is unaffected by fillReadBuffer()
1251 int oldReadBufferOffset
= d
->readBufferOffset
+ d
->readConverterSavedStateOffset
;
1252 while (d
->readBuffer
.size() < oldReadBufferOffset
) {
1253 if (!thatd
->fillReadBuffer(1))
1256 thatd
->readBufferOffset
= oldReadBufferOffset
;
1258 // Return the device position.
1259 return d
->device
->pos();
1263 return d
->stringOffset
;
1265 qWarning("QTextStream::pos: no device");
1270 Reads and discards whitespace from the stream until either a
1271 non-space character is detected, or until atEnd() returns
1272 true. This function is useful when reading a stream character by
1275 Whitespace characters are all characters for which
1276 QChar::isSpace() returns true.
1280 void QTextStream::skipWhiteSpace()
1283 CHECK_VALID_STREAM(Q_VOID
);
1284 d
->scan(0, 0, 0, QTextStreamPrivate::NotSpace
);
1285 d
->consumeLastToken();
1289 Sets the current device to \a device. If a device has already been
1290 assigned, QTextStream will call flush() before the old device is
1293 \note This function resets locale to the default locale ('C')
1294 and codec to the default codec, QTextCodec::codecForLocale().
1296 \sa device(), setString()
1298 void QTextStream::setDevice(QIODevice
*device
)
1302 if (d
->deleteDevice
) {
1303 #ifndef QT_NO_QOBJECT
1304 d
->deviceClosedNotifier
.disconnect();
1307 d
->deleteDevice
= false;
1313 d
->resetReadBuffer();
1314 #ifndef QT_NO_QOBJECT
1315 d
->deviceClosedNotifier
.setupDevice(this, d
->device
);
1320 Returns the current device associated with the QTextStream,
1321 or 0 if no device has been assigned.
1323 \sa setDevice(), string()
1325 QIODevice
*QTextStream::device() const
1327 Q_D(const QTextStream
);
1332 Sets the current string to \a string, using the given \a
1333 openMode. If a device has already been assigned, QTextStream will
1334 call flush() before replacing it.
1336 \sa string(), setDevice()
1338 void QTextStream::setString(QString
*string
, QIODevice::OpenMode openMode
)
1342 if (d
->deleteDevice
) {
1343 #ifndef QT_NO_QOBJECT
1344 d
->deviceClosedNotifier
.disconnect();
1345 d
->device
->blockSignals(true);
1348 d
->deleteDevice
= false;
1354 d
->stringOpenMode
= openMode
;
1358 Returns the current string assigned to the QTextStream, or 0 if no
1359 string has been assigned.
1361 \sa setString(), device()
1363 QString
*QTextStream::string() const
1365 Q_D(const QTextStream
);
1370 Sets the field alignment to \a mode. When used together with
1371 setFieldWidth(), this function allows you to generate formatted
1372 output with text aligned to the left, to the right or center
1375 \sa fieldAlignment(), setFieldWidth()
1377 void QTextStream::setFieldAlignment(FieldAlignment mode
)
1380 d
->fieldAlignment
= mode
;
1384 Returns the current field alignment.
1386 \sa setFieldAlignment(), fieldWidth()
1388 QTextStream::FieldAlignment
QTextStream::fieldAlignment() const
1390 Q_D(const QTextStream
);
1391 return d
->fieldAlignment
;
1395 Sets the pad character to \a ch. The default value is the ASCII
1396 space character (' '), or QChar(0x20). This character is used to
1397 fill in the space in fields when generating text.
1401 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 5
1403 The string \c s contains:
1405 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 6
1407 \sa padChar(), setFieldWidth()
1409 void QTextStream::setPadChar(QChar ch
)
1416 Returns the current pad character.
1418 \sa setPadChar(), setFieldWidth()
1420 QChar
QTextStream::padChar() const
1422 Q_D(const QTextStream
);
1427 Sets the current field width to \a width. If \a width is 0 (the
1428 default), the field width is equal to the length of the generated
1431 \note The field width applies to every element appended to this
1432 stream after this function has been called (e.g., it also pads
1433 endl). This behavior is different from similar classes in the STL,
1434 where the field width only applies to the next element.
1436 \sa fieldWidth(), setPadChar()
1438 void QTextStream::setFieldWidth(int width
)
1441 d
->fieldWidth
= width
;
1445 Returns the current field width.
1449 int QTextStream::fieldWidth() const
1451 Q_D(const QTextStream
);
1452 return d
->fieldWidth
;
1456 Sets the current number flags to \a flags. \a flags is a set of
1457 flags from the NumberFlag enum, and describes options for
1458 formatting generated code (e.g., whether or not to always write
1459 the base or sign of a number).
1461 \sa numberFlags(), setIntegerBase(), setRealNumberNotation()
1463 void QTextStream::setNumberFlags(NumberFlags flags
)
1466 d
->numberFlags
= flags
;
1470 Returns the current number flags.
1472 \sa setNumberFlags(), integerBase(), realNumberNotation()
1474 QTextStream::NumberFlags
QTextStream::numberFlags() const
1476 Q_D(const QTextStream
);
1477 return d
->numberFlags
;
1481 Sets the base of integers to \a base, both for reading and for
1482 generating numbers. \a base can be either 2 (binary), 8 (octal),
1483 10 (decimal) or 16 (hexadecimal). If \a base is 0, QTextStream
1484 will attempt to detect the base by inspecting the data on the
1485 stream. When generating numbers, QTextStream assumes base is 10
1486 unless the base has been set explicitly.
1488 \sa integerBase(), QString::number(), setNumberFlags()
1490 void QTextStream::setIntegerBase(int base
)
1493 d
->integerBase
= base
;
1497 Returns the current base of integers. 0 means that the base is
1498 detected when reading, or 10 (decimal) when generating numbers.
1500 \sa setIntegerBase(), QString::number(), numberFlags()
1502 int QTextStream::integerBase() const
1504 Q_D(const QTextStream
);
1505 return d
->integerBase
;
1509 Sets the real number notation to \a notation (SmartNotation,
1510 FixedNotation, ScientificNotation). When reading and generating
1511 numbers, QTextStream uses this value to detect the formatting of
1514 \sa realNumberNotation(), setRealNumberPrecision(), setNumberFlags(), setIntegerBase()
1516 void QTextStream::setRealNumberNotation(RealNumberNotation notation
)
1519 d
->realNumberNotation
= notation
;
1523 Returns the current real number notation.
1525 \sa setRealNumberNotation(), realNumberPrecision(), numberFlags(), integerBase()
1527 QTextStream::RealNumberNotation
QTextStream::realNumberNotation() const
1529 Q_D(const QTextStream
);
1530 return d
->realNumberNotation
;
1534 Sets the precision of real numbers to \a precision. This value
1535 describes the number of fraction digits QTextStream should
1536 write when generating real numbers.
1538 The precision cannot be a negative value. The default value is 6.
1540 \sa realNumberPrecision(), setRealNumberNotation()
1542 void QTextStream::setRealNumberPrecision(int precision
)
1545 if (precision
< 0) {
1546 qWarning("QTextStream::setRealNumberPrecision: Invalid precision (%d)", precision
);
1547 d
->realNumberPrecision
= 6;
1550 d
->realNumberPrecision
= precision
;
1554 Returns the current real number precision, or the number of fraction
1555 digits QTextStream will write when generating real numbers.
1557 \sa setRealNumberNotation(), realNumberNotation(), numberFlags(), integerBase()
1559 int QTextStream::realNumberPrecision() const
1561 Q_D(const QTextStream
);
1562 return d
->realNumberPrecision
;
1566 Returns the status of the text stream.
1568 \sa QTextStream::Status, setStatus(), resetStatus()
1571 QTextStream::Status
QTextStream::status() const
1573 Q_D(const QTextStream
);
1580 Resets the status of the text stream.
1582 \sa QTextStream::Status, status(), setStatus()
1584 void QTextStream::resetStatus()
1593 Sets the status of the text stream to the \a status given.
1595 \sa Status status() resetStatus()
1597 void QTextStream::setStatus(Status status
)
1600 if (d
->status
== Ok
)
1605 Returns true if there is no more data to be read from the
1606 QTextStream; otherwise returns false. This is similar to, but not
1607 the same as calling QIODevice::atEnd(), as QTextStream also takes
1608 into account its internal Unicode buffer.
1610 bool QTextStream::atEnd() const
1612 Q_D(const QTextStream
);
1613 CHECK_VALID_STREAM(true);
1616 return d
->string
->size() == d
->stringOffset
;
1617 return d
->readBuffer
.isEmpty() && d
->device
->atEnd();
1621 Reads the entire content of the stream, and returns it as a
1622 QString. Avoid this function when working on large files, as it
1623 will consume a significant amount of memory.
1625 Calling readLine() is better if you do not know how much data is
1630 QString
QTextStream::readAll()
1633 CHECK_VALID_STREAM(QString());
1635 return d
->read(INT_MAX
);
1639 Reads one line of text from the stream, and returns it as a
1640 QString. The maximum allowed line length is set to \a maxlen. If
1641 the stream contains lines longer than this, then the lines will be
1642 split after \a maxlen characters and returned in parts.
1644 If \a maxlen is 0, the lines can be of any length. A common value
1645 for \a maxlen is 75.
1647 The returned line has no trailing end-of-line characters ("\\n"
1648 or "\\r\\n"), so calling QString::trimmed() is unnecessary.
1650 If the stream has read to the end of the file, readLine() will return a
1651 null QString. For strings, or for devices that support it, you can
1652 explicitly test for the end of the stream using atEnd().
1654 \sa readAll(), QIODevice::readLine()
1656 QString
QTextStream::readLine(qint64 maxlen
)
1659 CHECK_VALID_STREAM(QString());
1661 const QChar
*readPtr
;
1663 if (!d
->scan(&readPtr
, &length
, int(maxlen
), QTextStreamPrivate::EndOfLine
))
1666 QString tmp
= QString(readPtr
, length
);
1667 d
->consumeLastToken();
1674 Reads at most \a maxlen characters from the stream, and returns the data
1677 \sa readAll(), readLine(), QIODevice::read()
1679 QString
QTextStream::read(qint64 maxlen
)
1682 CHECK_VALID_STREAM(QString());
1685 return QString::fromLatin1(""); // empty, not null
1687 return d
->read(int(maxlen
));
1692 QTextStreamPrivate::NumberParsingStatus
QTextStreamPrivate::getNumber(qulonglong
*ret
)
1694 scan(0, 0, 0, NotSpace
);
1697 // detect int encoding
1698 int base
= integerBase
;
1702 return npsInvalidPrefix
;
1703 if (ch
== QLatin1Char('0')) {
1705 if (!getChar(&ch2
)) {
1706 // Result is the number 0
1710 ch2
= ch2
.toLower();
1712 if (ch2
== QLatin1Char('x')) {
1714 } else if (ch2
== QLatin1Char('b')) {
1716 } else if (ch2
.isDigit() && ch2
.digitValue() >= 0 && ch2
.digitValue() <= 7) {
1722 } else if (ch
== locale
.negativeSign() || ch
== locale
.positiveSign() || ch
.isDigit()) {
1726 return npsInvalidPrefix
;
1729 // State of the stream is now the same as on entry
1730 // (cursor is at prefix),
1731 // and local variable 'base' has been set appropriately.
1737 QChar pf1
, pf2
, dig
;
1738 // Parse prefix '0b'
1739 if (!getChar(&pf1
) || pf1
!= QLatin1Char('0'))
1740 return npsInvalidPrefix
;
1741 if (!getChar(&pf2
) || pf2
.toLower() != QLatin1Char('b'))
1742 return npsInvalidPrefix
;
1745 while (getChar(&dig
)) {
1746 int n
= dig
.toLower().unicode();
1747 if (n
== '0' || n
== '1') {
1757 // Unwind the prefix and abort
1760 return npsMissingDigit
;
1767 if (!getChar(&pf
) || pf
!= QLatin1Char('0'))
1768 return npsInvalidPrefix
;
1771 while (getChar(&dig
)) {
1772 int n
= dig
.toLower().unicode();
1773 if (n
>= '0' && n
<= '7') {
1783 // Unwind the prefix and abort
1785 return npsMissingDigit
;
1790 // Parse sign (or first digit)
1793 if (!getChar(&sign
))
1794 return npsMissingDigit
;
1795 if (sign
!= locale
.negativeSign() && sign
!= locale
.positiveSign()) {
1796 if (!sign
.isDigit()) {
1798 return npsMissingDigit
;
1800 val
+= sign
.digitValue();
1805 while (getChar(&ch
)) {
1808 val
+= ch
.digitValue();
1809 } else if (locale
!= QLocale::c() && ch
== locale
.groupSeparator()) {
1818 return npsMissingDigit
;
1819 if (sign
== locale
.negativeSign()) {
1820 qlonglong ival
= qlonglong(val
);
1823 val
= qulonglong(ival
);
1828 QChar pf1
, pf2
, dig
;
1829 // Parse prefix ' 0x'
1830 if (!getChar(&pf1
) || pf1
!= QLatin1Char('0'))
1831 return npsInvalidPrefix
;
1832 if (!getChar(&pf2
) || pf2
.toLower() != QLatin1Char('x'))
1833 return npsInvalidPrefix
;
1836 while (getChar(&dig
)) {
1837 int n
= dig
.toLower().unicode();
1838 if (n
>= '0' && n
<= '9') {
1841 } else if (n
>= 'a' && n
<= 'f') {
1843 val
+= 10 + (n
- 'a');
1851 return npsMissingDigit
;
1856 // Unsupported integerBase
1857 return npsInvalidPrefix
;
1868 bool QTextStreamPrivate::getReal(double *f
)
1870 // We use a table-driven FSM to parse floating point numbers
1871 // strtod() cannot be used directly since we may be reading from a
1902 static const uchar table
[13][10] = {
1903 // None InputSign InputDigit InputDot InputExp InputI InputN InputF InputA InputT
1904 { 0, Sign
, Mantissa
, Dot
, 0, Inf1
, Nan1
, 0, 0, 0 }, // 0 Init
1905 { 0, 0, Mantissa
, Dot
, 0, Inf1
, Nan1
, 0, 0, 0 }, // 1 Sign
1906 { Done
, Done
, Mantissa
, Dot
, ExpMark
, 0, 0, 0, 0, 0 }, // 2 Mantissa
1907 { 0, 0, Abscissa
, 0, 0, 0, 0, 0, 0, 0 }, // 3 Dot
1908 { Done
, Done
, Abscissa
, Done
, ExpMark
, 0, 0, 0, 0, 0 }, // 4 Abscissa
1909 { 0, ExpSign
, Exponent
, 0, 0, 0, 0, 0, 0, 0 }, // 5 ExpMark
1910 { 0, 0, Exponent
, 0, 0, 0, 0, 0, 0, 0 }, // 6 ExpSign
1911 { Done
, Done
, Exponent
, Done
, Done
, 0, 0, 0, 0, 0 }, // 7 Exponent
1912 { 0, 0, 0, 0, 0, 0, 0, 0, Nan2
, 0 }, // 8 Nan1
1913 { 0, 0, 0, 0, 0, 0, NanInf
, 0, 0, 0 }, // 9 Nan2
1914 { 0, 0, 0, 0, 0, 0, Inf2
, 0, 0, 0 }, // 10 Inf1
1915 { 0, 0, 0, 0, 0, 0, 0, NanInf
, 0, 0 }, // 11 Inf2
1916 { Done
, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // 11 NanInf
1919 ParserState state
= Init
;
1920 InputToken input
= None
;
1922 scan(0, 0, 0, NotSpace
);
1925 const int BufferSize
= 128;
1926 char buf
[BufferSize
];
1930 while (getChar(&c
)) {
1931 switch (c
.unicode()) {
1932 case '0': case '1': case '2': case '3': case '4':
1933 case '5': case '6': case '7': case '8': case '9':
1952 QChar lc
= c
.toLower();
1953 if (lc
== locale
.decimalPoint().toLower())
1955 else if (lc
== locale
.exponential().toLower())
1957 else if (lc
== locale
.negativeSign().toLower()
1958 || lc
== locale
.positiveSign().toLower())
1960 else if (locale
!= QLocale::c() // backward-compatibility
1961 && lc
== locale
.groupSeparator().toLower())
1962 input
= InputDigit
; // well, it isn't a digit, but no one cares.
1969 state
= ParserState(table
[state
][input
]);
1971 if (state
== Init
|| state
== Done
|| i
> (BufferSize
- 5)) {
1973 if (i
> (BufferSize
- 5)) { // ignore rest of digits
1974 while (getChar(&c
)) {
1984 buf
[i
++] = c
.toLatin1();
1993 // backward-compatibility. Old implmentation supported +nan/-nan
1994 // for some reason. QLocale only checks for lower-case
1995 // nan/+inf/-inf, so here we also check for uppercase and mixed
1997 if (!qstricmp(buf
, "nan") || !qstricmp(buf
, "+nan") || !qstricmp(buf
, "-nan")) {
2000 } else if (!qstricmp(buf
, "+inf") || !qstricmp(buf
, "inf")) {
2003 } else if (!qstricmp(buf
, "-inf")) {
2008 *f
= locale
.toDouble(QString::fromLatin1(buf
), &ok
);
2013 Reads a character from the stream and stores it in \a c. Returns a
2014 reference to the QTextStream, so several operators can be
2017 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 7
2019 Whitespace is \e not skipped.
2022 QTextStream
&QTextStream::operator>>(QChar
&c
)
2025 CHECK_VALID_STREAM(*this);
2026 d
->scan(0, 0, 0, QTextStreamPrivate::NotSpace
);
2027 if (!d
->getChar(&c
))
2028 setStatus(ReadPastEnd
);
2035 Reads a character from the stream and stores it in \a c. The
2036 character from the stream is converted to ISO-5589-1 before it is
2039 \sa QChar::toLatin1()
2041 QTextStream
&QTextStream::operator>>(char &c
)
2050 Reads an integer from the stream and stores it in \a i, then
2051 returns a reference to the QTextStream. The number is cast to
2052 the correct type before it is stored. If no number was detected on
2053 the stream, \a i is set to 0.
2055 By default, QTextStream will attempt to detect the base of the
2056 number using the following rules:
2059 \header \o Prefix \o Base
2060 \row \o "0b" or "0B" \o 2 (binary)
2061 \row \o "0" followed by "0-7" \o 8 (octal)
2062 \row \o "0" otherwise \o 10 (decimal)
2063 \row \o "0x" or "0X" \o 16 (hexadecimal)
2064 \row \o "1" to "9" \o 10 (decimal)
2067 By calling setIntegerBase(), you can specify the integer base
2068 explicitly. This will disable the auto-detection, and speed up
2069 QTextStream slightly.
2071 Leading whitespace is skipped.
2073 QTextStream
&QTextStream::operator>>(signed short &i
)
2075 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed short);
2081 Stores the integer in the unsigned short \a i.
2083 QTextStream
&QTextStream::operator>>(unsigned short &i
)
2085 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned short);
2091 Stores the integer in the signed int \a i.
2093 QTextStream
&QTextStream::operator>>(signed int &i
)
2095 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed int);
2101 Stores the integer in the unsigned int \a i.
2103 QTextStream
&QTextStream::operator>>(unsigned int &i
)
2105 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned int);
2111 Stores the integer in the signed long \a i.
2113 QTextStream
&QTextStream::operator>>(signed long &i
)
2115 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed long);
2121 Stores the integer in the unsigned long \a i.
2123 QTextStream
&QTextStream::operator>>(unsigned long &i
)
2125 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned long);
2131 Stores the integer in the qlonglong \a i.
2133 QTextStream
&QTextStream::operator>>(qlonglong
&i
)
2135 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(qlonglong
);
2141 Stores the integer in the qulonglong \a i.
2143 QTextStream
&QTextStream::operator>>(qulonglong
&i
)
2145 IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(qulonglong
);
2149 Reads a real number from the stream and stores it in \a f, then
2150 returns a reference to the QTextStream. The number is cast to
2151 the correct type. If no real number is detect on the stream, \a f
2154 As a special exception, QTextStream allows the strings "nan" and "inf" to
2155 represent NAN and INF floats or doubles.
2157 Leading whitespace is skipped.
2159 QTextStream
&QTextStream::operator>>(float &f
)
2161 IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(float);
2167 Stores the real number in the double \a f.
2169 QTextStream
&QTextStream::operator>>(double &f
)
2171 IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(double);
2175 Reads a word from the stream and stores it in \a str, then returns
2176 a reference to the stream. Words are separated by whitespace
2177 (i.e., all characters for which QChar::isSpace() returns true).
2179 Leading whitespace is skipped.
2181 QTextStream
&QTextStream::operator>>(QString
&str
)
2184 CHECK_VALID_STREAM(*this);
2187 d
->scan(0, 0, 0, QTextStreamPrivate::NotSpace
);
2188 d
->consumeLastToken();
2192 if (!d
->scan(&ptr
, &length
, 0, QTextStreamPrivate::Space
)) {
2193 setStatus(ReadPastEnd
);
2197 str
= QString(ptr
, length
);
2198 d
->consumeLastToken();
2205 Converts the word to ISO-8859-1, then stores it in \a array.
2207 \sa QString::toLatin1()
2209 QTextStream
&QTextStream::operator>>(QByteArray
&array
)
2212 CHECK_VALID_STREAM(*this);
2215 d
->scan(0, 0, 0, QTextStreamPrivate::NotSpace
);
2216 d
->consumeLastToken();
2220 if (!d
->scan(&ptr
, &length
, 0, QTextStreamPrivate::Space
)) {
2221 setStatus(ReadPastEnd
);
2225 for (int i
= 0; i
< length
; ++i
)
2226 array
+= ptr
[i
].toLatin1();
2228 d
->consumeLastToken();
2235 Stores the word in \a c, terminated by a '\0' character. If no word is
2236 available, only the '\0' character is stored.
2238 Warning: Although convenient, this operator is dangerous and must
2239 be used with care. QTextStream assumes that \a c points to a
2240 buffer with enough space to hold the word. If the buffer is too
2241 small, your application may crash.
2243 If possible, use the QByteArray operator instead.
2245 QTextStream
&QTextStream::operator>>(char *c
)
2249 CHECK_VALID_STREAM(*this);
2250 d
->scan(0, 0, 0, QTextStreamPrivate::NotSpace
);
2251 d
->consumeLastToken();
2255 if (!d
->scan(&ptr
, &length
, 0, QTextStreamPrivate::Space
)) {
2256 setStatus(ReadPastEnd
);
2260 for (int i
= 0; i
< length
; ++i
)
2261 *c
++ = ptr
[i
].toLatin1();
2263 d
->consumeLastToken();
2269 bool QTextStreamPrivate::putNumber(qulonglong number
, bool negative
)
2274 if (numberFlags
& QTextStream::ShowBase
)
2275 flags
|= QLocalePrivate::ShowBase
;
2276 if (numberFlags
& QTextStream::ForceSign
)
2277 flags
|= QLocalePrivate::AlwaysShowSign
;
2278 if (numberFlags
& QTextStream::UppercaseBase
)
2279 flags
|= QLocalePrivate::UppercaseBase
;
2280 if (numberFlags
& QTextStream::UppercaseDigits
)
2281 flags
|= QLocalePrivate::CapitalEorX
;
2283 // add thousands group separators. For backward compatibility we
2284 // don't add a group separator for C locale.
2285 if (locale
!= QLocale::c())
2286 flags
|= QLocalePrivate::ThousandsGroup
;
2288 const QLocalePrivate
*dd
= locale
.d();
2289 int base
= integerBase
? integerBase
: 10;
2290 if (negative
&& base
== 10) {
2291 result
= dd
->longLongToString(-static_cast<qlonglong
>(number
), -1,
2293 } else if (negative
) {
2294 // Workaround for backward compatibility for writing negative
2295 // numbers in octal and hex:
2296 // QTextStream(result) << showbase << hex << -1 << oct << -1
2297 // should output: -0x1 -0b1
2298 result
= dd
->unsLongLongToString(number
, -1, base
, -1, flags
);
2299 result
.prepend(locale
.negativeSign());
2301 result
= dd
->unsLongLongToString(number
, -1, base
, -1, flags
);
2302 // workaround for backward compatibility - in octal form with
2303 // ShowBase flag set zero should be written as '00'
2304 if (number
== 0 && base
== 8 && numberFlags
& QTextStream::ShowBase
2305 && result
== QLatin1String("0")) {
2306 result
.prepend(QLatin1Char('0'));
2309 return putString(result
, true);
2316 QTextStream
&QTextStream::operator<<(QBool b
)
2318 return *this << bool(b
);
2322 Writes the character \a c to the stream, then returns a reference
2327 QTextStream
&QTextStream::operator<<(QChar c
)
2330 CHECK_VALID_STREAM(*this);
2331 d
->putString(QString(c
));
2338 Converts \a c from ASCII to a QChar, then writes it to the stream.
2340 QTextStream
&QTextStream::operator<<(char c
)
2343 CHECK_VALID_STREAM(*this);
2344 d
->putString(QString(QChar::fromAscii(c
)));
2349 Writes the integer number \a i to the stream, then returns a
2350 reference to the QTextStream. By default, the number is stored in
2351 decimal form, but you can also set the base by calling
2354 \sa setFieldWidth(), setNumberFlags()
2356 QTextStream
&QTextStream::operator<<(signed short i
)
2359 CHECK_VALID_STREAM(*this);
2360 d
->putNumber((qulonglong
)qAbs(qlonglong(i
)), i
< 0);
2367 Writes the unsigned short \a i to the stream.
2369 QTextStream
&QTextStream::operator<<(unsigned short i
)
2372 CHECK_VALID_STREAM(*this);
2373 d
->putNumber((qulonglong
)i
, false);
2380 Writes the signed int \a i to the stream.
2382 QTextStream
&QTextStream::operator<<(signed int i
)
2385 CHECK_VALID_STREAM(*this);
2386 d
->putNumber((qulonglong
)qAbs(qlonglong(i
)), i
< 0);
2393 Writes the unsigned int \a i to the stream.
2395 QTextStream
&QTextStream::operator<<(unsigned int i
)
2398 CHECK_VALID_STREAM(*this);
2399 d
->putNumber((qulonglong
)i
, false);
2406 Writes the signed long \a i to the stream.
2408 QTextStream
&QTextStream::operator<<(signed long i
)
2411 CHECK_VALID_STREAM(*this);
2412 d
->putNumber((qulonglong
)qAbs(qlonglong(i
)), i
< 0);
2419 Writes the unsigned long \a i to the stream.
2421 QTextStream
&QTextStream::operator<<(unsigned long i
)
2424 CHECK_VALID_STREAM(*this);
2425 d
->putNumber((qulonglong
)i
, false);
2432 Writes the qlonglong \a i to the stream.
2434 QTextStream
&QTextStream::operator<<(qlonglong i
)
2437 CHECK_VALID_STREAM(*this);
2438 d
->putNumber((qulonglong
)qAbs(i
), i
< 0);
2445 Writes the qulonglong \a i to the stream.
2447 QTextStream
&QTextStream::operator<<(qulonglong i
)
2450 CHECK_VALID_STREAM(*this);
2451 d
->putNumber(i
, false);
2456 Writes the real number \a f to the stream, then returns a
2457 reference to the QTextStream. By default, QTextStream stores it
2458 using SmartNotation, with up to 6 digits of precision. You can
2459 change the textual representation QTextStream will use for real
2460 numbers by calling setRealNumberNotation(),
2461 setRealNumberPrecision() and setNumberFlags().
2463 \sa setFieldWidth(), setRealNumberNotation(),
2464 setRealNumberPrecision(), setNumberFlags()
2466 QTextStream
&QTextStream::operator<<(float f
)
2468 return *this << double(f
);
2474 Writes the double \a f to the stream.
2476 QTextStream
&QTextStream::operator<<(double f
)
2479 CHECK_VALID_STREAM(*this);
2481 QLocalePrivate::DoubleForm form
= QLocalePrivate::DFDecimal
;
2482 switch (realNumberNotation()) {
2484 form
= QLocalePrivate::DFDecimal
;
2486 case ScientificNotation
:
2487 form
= QLocalePrivate::DFExponent
;
2490 form
= QLocalePrivate::DFSignificantDigits
;
2495 if (numberFlags() & ShowBase
)
2496 flags
|= QLocalePrivate::ShowBase
;
2497 if (numberFlags() & ForceSign
)
2498 flags
|= QLocalePrivate::AlwaysShowSign
;
2499 if (numberFlags() & UppercaseBase
)
2500 flags
|= QLocalePrivate::UppercaseBase
;
2501 if (numberFlags() & UppercaseDigits
)
2502 flags
|= QLocalePrivate::CapitalEorX
;
2503 if (numberFlags() & ForcePoint
)
2504 flags
|= QLocalePrivate::Alternate
;
2506 const QLocalePrivate
*dd
= d
->locale
.d();
2507 QString num
= dd
->doubleToString(f
, d
->realNumberPrecision
, form
, -1, flags
);
2508 d
->putString(num
, true);
2513 Writes the string \a string to the stream, and returns a reference
2514 to the QTextStream. The string is first encoded using the assigned
2515 codec (the default codec is QTextCodec::codecForLocale()) before
2516 it is written to the stream.
2518 \sa setFieldWidth(), setCodec()
2520 QTextStream
&QTextStream::operator<<(const QString
&string
)
2523 CHECK_VALID_STREAM(*this);
2524 d
->putString(string
);
2531 Writes \a array to the stream. The contents of \a array are
2532 converted with QString::fromAscii().
2534 QTextStream
&QTextStream::operator<<(const QByteArray
&array
)
2537 CHECK_VALID_STREAM(*this);
2538 d
->putString(QString::fromAscii(array
.constData(), array
.length()));
2545 Writes the constant string pointed to by \a string to the stream. \a
2546 string is assumed to be in ISO-8859-1 encoding. This operator
2547 is convenient when working with constant string data. Example:
2549 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 8
2551 Warning: QTextStream assumes that \a string points to a string of
2552 text, terminated by a '\0' character. If there is no terminating
2553 '\0' character, your application may crash.
2555 QTextStream
&QTextStream::operator<<(const char *string
)
2558 CHECK_VALID_STREAM(*this);
2559 d
->putString(QLatin1String(string
));
2566 Writes \a ptr to the stream as a hexadecimal number with a base.
2569 QTextStream
&QTextStream::operator<<(const void *ptr
)
2572 CHECK_VALID_STREAM(*this);
2573 int oldBase
= d
->integerBase
;
2574 NumberFlags oldFlags
= d
->numberFlags
;
2575 d
->integerBase
= 16;
2576 d
->numberFlags
|= ShowBase
;
2577 d
->putNumber(reinterpret_cast<quintptr
>(ptr
), false);
2578 d
->integerBase
= oldBase
;
2579 d
->numberFlags
= oldFlags
;
2584 \relates QTextStream
2586 Calls QTextStream::setIntegerBase(2) on \a stream and returns \a
2589 \sa oct(), dec(), hex(), {QTextStream manipulators}
2591 QTextStream
&bin(QTextStream
&stream
)
2593 stream
.setIntegerBase(2);
2598 \relates QTextStream
2600 Calls QTextStream::setIntegerBase(8) on \a stream and returns \a
2603 \sa bin(), dec(), hex(), {QTextStream manipulators}
2605 QTextStream
&oct(QTextStream
&stream
)
2607 stream
.setIntegerBase(8);
2612 \relates QTextStream
2614 Calls QTextStream::setIntegerBase(10) on \a stream and returns \a
2617 \sa bin(), oct(), hex(), {QTextStream manipulators}
2619 QTextStream
&dec(QTextStream
&stream
)
2621 stream
.setIntegerBase(10);
2626 \relates QTextStream
2628 Calls QTextStream::setIntegerBase(16) on \a stream and returns \a
2631 \note The hex modifier can only be used for writing to streams.
2632 \sa bin(), oct(), dec(), {QTextStream manipulators}
2634 QTextStream
&hex(QTextStream
&stream
)
2636 stream
.setIntegerBase(16);
2641 \relates QTextStream
2643 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2644 QTextStream::ShowBase) on \a stream and returns \a stream.
2646 \sa noshowbase(), forcesign(), forcepoint(), {QTextStream manipulators}
2648 QTextStream
&showbase(QTextStream
&stream
)
2650 stream
.setNumberFlags(stream
.numberFlags() | QTextStream::ShowBase
);
2655 \relates QTextStream
2657 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2658 QTextStream::ForceSign) on \a stream and returns \a stream.
2660 \sa noforcesign(), forcepoint(), showbase(), {QTextStream manipulators}
2662 QTextStream
&forcesign(QTextStream
&stream
)
2664 stream
.setNumberFlags(stream
.numberFlags() | QTextStream::ForceSign
);
2669 \relates QTextStream
2671 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2672 QTextStream::ForcePoint) on \a stream and returns \a stream.
2674 \sa noforcepoint(), forcesign(), showbase(), {QTextStream manipulators}
2676 QTextStream
&forcepoint(QTextStream
&stream
)
2678 stream
.setNumberFlags(stream
.numberFlags() | QTextStream::ForcePoint
);
2683 \relates QTextStream
2685 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2686 ~QTextStream::ShowBase) on \a stream and returns \a stream.
2688 \sa showbase(), noforcesign(), noforcepoint(), {QTextStream manipulators}
2690 QTextStream
&noshowbase(QTextStream
&stream
)
2692 stream
.setNumberFlags(stream
.numberFlags() &= ~QTextStream::ShowBase
);
2697 \relates QTextStream
2699 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2700 ~QTextStream::ForceSign) on \a stream and returns \a stream.
2702 \sa forcesign(), noforcepoint(), noshowbase(), {QTextStream manipulators}
2704 QTextStream
&noforcesign(QTextStream
&stream
)
2706 stream
.setNumberFlags(stream
.numberFlags() &= ~QTextStream::ForceSign
);
2711 \relates QTextStream
2713 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2714 ~QTextStream::ForcePoint) on \a stream and returns \a stream.
2716 \sa forcepoint(), noforcesign(), noshowbase(), {QTextStream manipulators}
2718 QTextStream
&noforcepoint(QTextStream
&stream
)
2720 stream
.setNumberFlags(stream
.numberFlags() &= ~QTextStream::ForcePoint
);
2725 \relates QTextStream
2727 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2728 QTextStream::UppercaseBase) on \a stream and returns \a stream.
2730 \sa lowercasebase(), uppercasedigits(), {QTextStream manipulators}
2732 QTextStream
&uppercasebase(QTextStream
&stream
)
2734 stream
.setNumberFlags(stream
.numberFlags() | QTextStream::UppercaseBase
);
2739 \relates QTextStream
2741 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2742 QTextStream::UppercaseDigits) on \a stream and returns \a stream.
2744 \sa lowercasedigits(), uppercasebase(), {QTextStream manipulators}
2746 QTextStream
&uppercasedigits(QTextStream
&stream
)
2748 stream
.setNumberFlags(stream
.numberFlags() | QTextStream::UppercaseDigits
);
2753 \relates QTextStream
2755 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2756 ~QTextStream::UppercaseBase) on \a stream and returns \a stream.
2758 \sa uppercasebase(), lowercasedigits(), {QTextStream manipulators}
2760 QTextStream
&lowercasebase(QTextStream
&stream
)
2762 stream
.setNumberFlags(stream
.numberFlags() & ~QTextStream::UppercaseBase
);
2767 \relates QTextStream
2769 Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2770 ~QTextStream::UppercaseDigits) on \a stream and returns \a stream.
2772 \sa uppercasedigits(), lowercasebase(), {QTextStream manipulators}
2774 QTextStream
&lowercasedigits(QTextStream
&stream
)
2776 stream
.setNumberFlags(stream
.numberFlags() & ~QTextStream::UppercaseDigits
);
2781 \relates QTextStream
2783 Calls QTextStream::setRealNumberNotation(QTextStream::FixedNotation)
2784 on \a stream and returns \a stream.
2786 \sa scientific(), {QTextStream manipulators}
2788 QTextStream
&fixed(QTextStream
&stream
)
2790 stream
.setRealNumberNotation(QTextStream::FixedNotation
);
2795 \relates QTextStream
2797 Calls QTextStream::setRealNumberNotation(QTextStream::ScientificNotation)
2798 on \a stream and returns \a stream.
2800 \sa fixed(), {QTextStream manipulators}
2802 QTextStream
&scientific(QTextStream
&stream
)
2804 stream
.setRealNumberNotation(QTextStream::ScientificNotation
);
2809 \relates QTextStream
2811 Calls QTextStream::setFieldAlignment(QTextStream::AlignLeft)
2812 on \a stream and returns \a stream.
2814 \sa right(), center(), {QTextStream manipulators}
2816 QTextStream
&left(QTextStream
&stream
)
2818 stream
.setFieldAlignment(QTextStream::AlignLeft
);
2823 \relates QTextStream
2825 Calls QTextStream::setFieldAlignment(QTextStream::AlignRight)
2826 on \a stream and returns \a stream.
2828 \sa left(), center(), {QTextStream manipulators}
2830 QTextStream
&right(QTextStream
&stream
)
2832 stream
.setFieldAlignment(QTextStream::AlignRight
);
2837 \relates QTextStream
2839 Calls QTextStream::setFieldAlignment(QTextStream::AlignCenter)
2840 on \a stream and returns \a stream.
2842 \sa left(), right(), {QTextStream manipulators}
2844 QTextStream
¢er(QTextStream
&stream
)
2846 stream
.setFieldAlignment(QTextStream::AlignCenter
);
2851 \relates QTextStream
2853 Writes '\n' to the \a stream and flushes the stream.
2857 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 9
2859 Note: On Windows, all '\n' characters are written as '\r\n' if
2860 QTextStream's device or string is opened using the QIODevice::Text flag.
2862 \sa flush(), reset(), {QTextStream manipulators}
2864 QTextStream
&endl(QTextStream
&stream
)
2866 return stream
<< QLatin1Char('\n') << flush
;
2870 \relates QTextStream
2872 Calls QTextStream::flush() on \a stream and returns \a stream.
2874 \sa endl(), reset(), {QTextStream manipulators}
2876 QTextStream
&flush(QTextStream
&stream
)
2883 \relates QTextStream
2885 Calls QTextStream::reset() on \a stream and returns \a stream.
2887 \sa flush(), {QTextStream manipulators}
2889 QTextStream
&reset(QTextStream
&stream
)
2896 \relates QTextStream
2898 Calls skipWhiteSpace() on \a stream and returns \a stream.
2900 \sa {QTextStream manipulators}
2902 QTextStream
&ws(QTextStream
&stream
)
2904 stream
.skipWhiteSpace();
2909 \fn QTextStreamManipulator qSetFieldWidth(int width)
2910 \relates QTextStream
2912 Equivalent to QTextStream::setFieldWidth(\a width).
2916 \fn QTextStreamManipulator qSetPadChar(QChar ch)
2917 \relates QTextStream
2919 Equivalent to QTextStream::setPadChar(\a ch).
2923 \fn QTextStreamManipulator qSetRealNumberPrecision(int precision)
2924 \relates QTextStream
2926 Equivalent to QTextStream::setRealNumberPrecision(\a precision).
2929 #ifndef QT_NO_TEXTCODEC
2931 \relates QTextStream
2933 Toggles insertion of the Byte Order Mark on \a stream when QTextStream is
2934 used with a UTF codec.
2936 \sa QTextStream::setGenerateByteOrderMark(), {QTextStream manipulators}
2938 QTextStream
&bom(QTextStream
&stream
)
2940 stream
.setGenerateByteOrderMark(true);
2945 Sets the codec for this stream to \a codec. The codec is used for
2946 decoding any data that is read from the assigned device, and for
2947 encoding any data that is written. By default,
2948 QTextCodec::codecForLocale() is used, and automatic unicode
2949 detection is enabled.
2951 If QTextStream operates on a string, this function does nothing.
2953 \warning If you call this function while the text stream is reading
2954 from an open sequential socket, the internal buffer may still contain
2955 text decoded using the old codec.
2957 \sa codec(), setAutoDetectUnicode(), setLocale()
2959 void QTextStream::setCodec(QTextCodec
*codec
)
2962 qint64 seekPos
= -1;
2963 if (!d
->readBuffer
.isEmpty()) {
2964 if (!d
->device
->isSequential()) {
2969 if (seekPos
>=0 && !d
->readBuffer
.isEmpty())
2974 Sets the codec for this stream to the QTextCodec for the encoding
2975 specified by \a codecName. Common values for \c codecName include
2976 "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding isn't
2977 recognized, nothing happens.
2981 \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 10
2983 \sa QTextCodec::codecForName(), setLocale()
2985 void QTextStream::setCodec(const char *codecName
)
2987 QTextCodec
*codec
= QTextCodec::codecForName(codecName
);
2993 Returns the codec that is current assigned to the stream.
2995 \sa setCodec(), setAutoDetectUnicode(), locale()
2997 QTextCodec
*QTextStream::codec() const
2999 Q_D(const QTextStream
);
3004 If \a enabled is true, QTextStream will attempt to detect Unicode
3005 encoding by peeking into the stream data to see if it can find the
3006 UTF-16 or UTF-32 BOM (Byte Order Mark). If this mark is found, QTextStream
3007 will replace the current codec with the UTF codec.
3009 This function can be used together with setCodec(). It is common
3010 to set the codec to UTF-8, and then enable UTF-16 detection.
3012 \sa autoDetectUnicode(), setCodec()
3014 void QTextStream::setAutoDetectUnicode(bool enabled
)
3017 d
->autoDetectUnicode
= enabled
;
3021 Returns true if automatic Unicode detection is enabled; otherwise
3024 \sa setAutoDetectUnicode(), setCodec()
3026 bool QTextStream::autoDetectUnicode() const
3028 Q_D(const QTextStream
);
3029 return d
->autoDetectUnicode
;
3033 If \a generate is true and a UTF codec is used, QTextStream will insert
3034 the BOM (Byte Order Mark) before any data has been written to the
3035 device. If \a generate is false, no BOM will be inserted. This function
3036 must be called before any data is written. Otherwise, it does nothing.
3038 \sa generateByteOrderMark(), bom()
3040 void QTextStream::setGenerateByteOrderMark(bool generate
)
3043 if (d
->writeBuffer
.isEmpty()) {
3045 d
->writeConverterState
.flags
&= ~QTextCodec::IgnoreHeader
;
3047 d
->writeConverterState
.flags
|= QTextCodec::IgnoreHeader
;
3052 Returns true if QTextStream is set to generate the UTF BOM (Byte Order
3053 Mark) when using a UTF codec; otherwise returns false.
3055 \sa setGenerateByteOrderMark()
3057 bool QTextStream::generateByteOrderMark() const
3059 Q_D(const QTextStream
);
3060 return (d
->writeConverterState
.flags
& QTextCodec::IgnoreHeader
) == 0;
3068 Sets the locale for this stream to \a locale. The specified locale is
3069 used for conversions between numbers and their string representations.
3071 The default locale is C and it is a special case - the thousands
3072 group separator is not used for backward compatibility reasons.
3076 void QTextStream::setLocale(const QLocale
&locale
)
3085 Returns the locale for this stream. The default locale is C.
3089 QLocale
QTextStream::locale() const
3091 Q_D(const QTextStream
);
3098 \brief The QTextIStream class is a convenience class for input streams.
3103 Use QTextStream instead.
3107 \fn QTextIStream::QTextIStream(const QString *string)
3109 Use QTextStream(&\a{string}, QIODevice::ReadOnly) instead.
3112 \fn QTextIStream::QTextIStream(QByteArray *byteArray)
3114 Use QTextStream(&\a{byteArray}, QIODevice::ReadOnly) instead.
3117 \fn QTextIStream::QTextIStream(FILE *file)
3119 Use QTextStream(\a{file}, QIODevice::ReadOnly) instead.
3124 \brief The QTextOStream class is a convenience class for output streams.
3129 Use QTextStream instead.
3133 \fn QTextOStream::QTextOStream(QString *string)
3135 Use QTextStream(&\a{string}, QIODevice::WriteOnly) instead.
3138 \fn QTextOStream::QTextOStream(QByteArray *byteArray)
3140 Use QTextStream(&\a{byteArray}, QIODevice::WriteOnly) instead.
3143 \fn QTextOStream::QTextOStream(FILE *file)
3145 Use QTextStream(\a{file}, QIODevice::WriteOnly) instead.
3150 int QTextStream::flagsInternal() const
3152 Q_D(const QTextStream
);
3155 switch (d
->fieldAlignment
) {
3156 case AlignLeft
: f
|= left
; break;
3157 case AlignRight
: f
|= right
; break;
3158 case AlignCenter
: f
|= internal
; break;
3162 switch (d
->integerBase
) {
3163 case 2: f
|= bin
; break;
3164 case 8: f
|= oct
; break;
3165 case 10: f
|= dec
; break;
3166 case 16: f
|= hex
; break;
3170 switch (d
->realNumberNotation
) {
3171 case FixedNotation
: f
|= fixed
; break;
3172 case ScientificNotation
: f
|= scientific
; break;
3176 if (d
->numberFlags
& ShowBase
)
3178 if (d
->numberFlags
& ForcePoint
)
3180 if (d
->numberFlags
& ForceSign
)
3182 if (d
->numberFlags
& UppercaseBase
)
3189 int QTextStream::flagsInternal(int newFlags
)
3191 int oldFlags
= flagsInternal();
3193 if (newFlags
& left
)
3194 setFieldAlignment(AlignLeft
);
3195 else if (newFlags
& right
)
3196 setFieldAlignment(AlignRight
);
3197 else if (newFlags
& internal
)
3198 setFieldAlignment(AlignCenter
);
3202 else if (newFlags
& oct
)
3204 else if (newFlags
& dec
)
3206 else if (newFlags
& hex
)
3209 if (newFlags
& showbase
)
3210 setNumberFlags(numberFlags() | ShowBase
);
3211 if (newFlags
& showpos
)
3212 setNumberFlags(numberFlags() | ForceSign
);
3213 if (newFlags
& showpoint
)
3214 setNumberFlags(numberFlags() | ForcePoint
);
3215 if (newFlags
& uppercase
)
3216 setNumberFlags(numberFlags() | UppercaseBase
);
3218 if (newFlags
& fixed
)
3219 setRealNumberNotation(FixedNotation
);
3220 else if (newFlags
& scientific
)
3221 setRealNumberNotation(ScientificNotation
);
3226 #ifndef QT_NO_TEXTCODEC
3228 Use setCodec() and setAutoDetectUnicode() instead.
3230 void QTextStream::setEncoding(Encoding encoding
)
3233 resetCodecConverterStateHelper(&d
->readConverterState
);
3234 resetCodecConverterStateHelper(&d
->writeConverterState
);
3238 d
->writeConverterState
.flags
|= QTextCodec::IgnoreHeader
;
3239 setCodec(QTextCodec::codecForLocale());
3240 d
->autoDetectUnicode
= true;
3243 d
->readConverterState
.flags
|= QTextCodec::IgnoreHeader
;
3244 d
->writeConverterState
.flags
|= QTextCodec::IgnoreHeader
;
3245 setCodec(QTextCodec::codecForName("ISO-8859-1"));
3246 d
->autoDetectUnicode
= false;
3249 setCodec(QTextCodec::codecForName("UTF-16"));
3250 d
->autoDetectUnicode
= false;
3253 d
->readConverterState
.flags
|= QTextCodec::IgnoreHeader
;
3254 d
->writeConverterState
.flags
|= QTextCodec::IgnoreHeader
;
3255 setCodec(QTextCodec::codecForName("UTF-16"));
3256 d
->autoDetectUnicode
= false;
3258 case UnicodeNetworkOrder
:
3259 d
->readConverterState
.flags
|= QTextCodec::IgnoreHeader
;
3260 d
->writeConverterState
.flags
|= QTextCodec::IgnoreHeader
;
3261 setCodec(QTextCodec::codecForName("UTF-16BE"));
3262 d
->autoDetectUnicode
= false;
3264 case UnicodeReverse
:
3265 d
->readConverterState
.flags
|= QTextCodec::IgnoreHeader
;
3266 d
->writeConverterState
.flags
|= QTextCodec::IgnoreHeader
;
3267 setCodec(QTextCodec::codecForName("UTF-16LE"));
3268 d
->autoDetectUnicode
= false;
3271 d
->writeConverterState
.flags
|= QTextCodec::IgnoreHeader
;
3272 setCodec(QTextCodec::codecForName("UTF-8"));
3273 d
->autoDetectUnicode
= true;
3280 \enum QTextStream::Encoding
3283 \value Latin1 Use setCodec(QTextCodec::codecForName("ISO-8859-1")) instead.
3284 \value Locale Use setCodec(QTextCodec::codecForLocale()) instead.
3285 \value RawUnicode Use setCodec(QTextCodec::codecForName("UTF-16")) instead.
3286 \value Unicode Use setCodec(QTextCodec::codecForName("UTF-16")) instead.
3287 \value UnicodeNetworkOrder Use setCodec(QTextCodec::codecForName("UTF-16BE")) instead.
3288 \value UnicodeReverse Use setCodec(QTextCodec::codecForName("UTF-16LE")) instead.
3289 \value UnicodeUTF8 Use setCodec(QTextCodec::codecForName("UTF-8")) instead.
3291 Also, for all encodings except QTextStream::Latin1 and
3292 QTextStream::UTF8, you need to call setAutoDetectUnicode(false)
3293 to obtain the Qt 3 behavior in addition to the setCodec() call.
3295 \sa setCodec(), setAutoDetectUnicode()
3299 \fn int QTextStream::flags() const
3301 Use fieldAlignment(), padChar(), fieldWidth(), numberFlags(),
3302 integerBase(), realNumberNotation(), and realNumberNotation
3307 \fn int QTextStream::flags(int)
3309 Use setFieldAlignment(), setPadChar(), setFieldWidth(),
3310 setNumberFlags(), setIntegerBase(), setRealNumberNotation(), and
3311 setRealNumberNotation instead.
3315 \fn int QTextStream::setf(int)
3317 Use setFieldAlignment(), setPadChar(), setFieldWidth(),
3318 setNumberFlags(), setIntegerBase(), setRealNumberNotation(), and
3319 setRealNumberNotation instead.
3323 \fn int QTextStream::setf(int, int)
3325 Use setFieldAlignment(), setPadChar(), setFieldWidth(),
3326 setNumberFlags(), setIntegerBase(), setRealNumberNotation(), and
3327 setRealNumberNotation instead.
3331 \fn int QTextStream::unsetf(int)
3333 Use setFieldAlignment(), setPadChar(), setFieldWidth(),
3334 setNumberFlags(), setIntegerBase(), setRealNumberNotation(), and
3335 setRealNumberNotation instead.
3339 \fn int QTextStream::width(int)
3341 Use setFieldWidth() instead.
3345 \fn int QTextStream::fill(int)
3347 Use setPadChar() instead.
3351 \fn int QTextStream::precision(int)
3353 Use setRealNumberPrecision() instead.
3357 \fn int QTextStream::read()
3359 Use readAll() or readLine() instead.
3363 \fn int QTextStream::unsetDevice()
3365 Use setDevice(0) instead.
3369 \variable QTextStream::skipws
3370 \variable QTextStream::left
3371 \variable QTextStream::right
3372 \variable QTextStream::internal
3373 \variable QTextStream::bin
3374 \variable QTextStream::oct
3375 \variable QTextStream::dec
3376 \variable QTextStream::hex
3377 \variable QTextStream::showbase
3378 \variable QTextStream::showpoint
3379 \variable QTextStream::uppercase
3380 \variable QTextStream::showpos
3381 \variable QTextStream::scientific
3382 \variable QTextStream::fixed
3383 \variable QTextStream::basefield
3384 \variable QTextStream::adjustfield
3385 \variable QTextStream::floatfield
3388 Use the new \l{QTextStream manipulators} instead.
3395 #ifndef QT_NO_QOBJECT
3396 #include "qtextstream.moc"